简体   繁体   中英

Malloc with a structure containing variably sized objects

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM