I want to save data in arrays called plist
. These arrays can vary in size and are part of a structure called ParticleList
. I know how to create one list of size n[0]
. n[0]
for example is of size 2. Thus, a list of size 2. But what do I have to do, if I want to create several lists with size n[0], n[1], n[2]
of type ParticleList
?
To cut a long story short: How should I modify my code in order to access lists of variable size somehow like pl[numberOfList].plist[PositionInArray] = -1
or `pl[numberOfList] -> plist[PositionInArray] = -1'
#include <stdlib.h>
#include <stdio.h>
typedef struct{
double *plist;
int plistSize;
} ParticleList;
void sendPar(int *n, int nl){
// Allocate memory for struct ParticleList
ParticleList *pl = malloc(sizeof(ParticleList));
// Allocate memory for list
pl->plist = malloc(sizeof(double)*n[0]);
// Fill list with data
for(int k=0; k<n[0]; k++){
pl->plist[k] = -1;
}
// Write size of list into file
pl->plistSize = n[0];
// Print data
printf("Content of list:\n");
for(int k=0; k<n[0]; k++){
printf("%lf\n", pl->plist[k]);
}
printf("Size of list: %d\n", pl->plistSize);
// Free memory
free(pl);
}
int main(){
// Number of lists
int nl = 3;
// Size of lists
int n[nl];
n[0] = 2;
n[1] = 3;
n[2] = 4;
sendPar(n, nl);
}
Do you mean something like this?
This way you can access each item in each list by
pl[<index of list>].plist[<index of list item>]
A bit more dynamic by using flexible array members (this way one of the lists can be replaced by another list of different size):
Note that I changed the struct!
It would seem you are looking for the language feature called flexible array member. It works like this:
Where
n
is the size you wantplist
to have.