Store data from struct in lists of variable size in C -
i want use mpi in project. in order send data processor, first have store particle data in list.
these lists can have variable size. want save data of struct:
typedef struct { double x[dim]; double v[dim]; double a[dim]; double m; } particle;
into list 'plist'. additionally want save size of list in plistsize
:
typedef struct{ double **plist; int plistsize; } particlelist;
i still newbie in c task somehow difficult me.
so far did following:
#include <stdlib.h> #include <stdio.h> #define dim 2 typedef struct{ double **plist; int plistsize; } particlelist; typedef struct { double x[dim]; double v[dim]; double a[dim]; double m; } particle; void sendpar(int *n, int npr, particle *p){ // allocate memory particlelist particlelist *pl = malloc(sizeof(pl)*npr); // allocate memory plistsize -> not work //for(int k=0; k<npr; k++){ // pl->plistsize[k] = malloc(sizeof(int*)); //} // allocate memory every list for(int k=0; k<npr; k++){ pl->plist[k] = malloc(sizeof(double*) * n[k]); } // write data list. for(int k=0; k<npr; k++){ for(int l=0; l<n[k]; l++){ int = 0; for(int d=0; d<dim; d++){ pl->plist[k][i] = p[k].x[d]; i++; } for(int d=0; d<dim; d++){ pl->plist[k][i] = p[k].v[d]; i++; } for(int d=0; d<dim; d++){ pl->plist[k][i] = p[k].a[d]; i++; } pl->plist[k][i] = p[k].m; } // pl->plistsize[k] = n[k]; } // free memory free(pl); } int main(){ // number of processors int npr = 3; // number of particles int np = 3; // allocate memory particles particle *p = malloc(sizeof(p)*np); for(int k=0; k<np; k++){ for(int d=0; d<dim; d++){ p[k].x[d] = 1000*k+100*d; p[k].v[d] = 10000*k+1000*d; p[k].a[d] = 10*k+d; } p[k].m = 100000+k; } // size of lists, in case every list has same length int n[npr]; n[0] = 10; n[1] = 10; n[2] = 10; sendpar(n, npr, p); // free memory free(p); }
i seg fault error. did wrong here:
// allocate memory particlelist particlelist *pl = malloc(sizeof(pl)*npr); // allocate memory every list for(int k=0; k<npr; k++){ pl->plist[k] = malloc(sizeof(double*) * n[k]); }
additionally not able allocate memory plistsize
. error warning: assignment makes integer pointer without cast
. see why?
Comments
Post a Comment