Reputation: 175
I'm trying to create a structure which contains information from each line in a file, so the size of the structure is dependent on the length of the file. C doesn't like me doing,
int makeStruct(int x){
typedef struct
{
int a[x], b[x];
char c[x], d[x];
char string[100][x];
} agentInfo;
return 0;
}
I know I have to Malloc, but I'm not sure what. Do I have to Malloc the structure and the arrays inside of it? I don't know how I'd Malloc the entire struct as I won't know how big it will be until I know x, so I can't use size-of? Any help appreciated.
Upvotes: 0
Views: 181
Reputation: 225052
You can't have multiple flexible array members in a C structure, so you'll have to go the route of allocating each member's array independently:
typedef struct
{
int *a, *b;
char *c, *d;
char (*string)[100];
} agentInfo;
int initStruct(agentInfo *ai, int x)
{
ai->a = malloc(x * sizeof(int));
ai->b = malloc(x * sizeof(int));
ai->c = malloc(x);
ai->d = malloc(x);
ai->string = malloc(100 * x);
return 0;
}
You'd use it something like:
agentInfo ai;
initStruct(&ai, 12);
Upvotes: 3