简体   繁体   中英

Accessing a Flexible array Member in C

I have a struct that looks like this:

typedef struct TestCase TestCase;
typedef struct TestCase {   
    char * userName;
    TestCase *c[];    // flexible array member
} TestCase;

And in another File I'm trying to set the flexible array member to NULL, but this doesn't seem to work (I'm not allowed to change how it's been defined)

void readIn(FILE * file, TestCase ** t) {
    *t = malloc(sizeof(TestCase));

    (*t)->c = NULL; //gives the error

}

I'm using double pointers because that's what's been specified for me (This isn't the entire code, but just a snipit). (As there is also code later to free the variables allocated).

Any help would be greatly appreciated.

Take a look at this line:

 (*t)->c = NULL;

This tries to assign NULL to an array, which isn't allowed. It would be like writing something like this:

int array[137];
array = NULL; // Not allowed

When you have a flexible array member, the intent is that when you malloc memory for the object, you overallocate the memory you need to make room for the array elements. For example, this code

*t = malloc(sizeof(TestCase) + numArrayElems * sizeof(TestCase*));

will allocate a new TestCase which has an array of numArrayElems pointers.

If you don't know in advance how many pointers you'll need, then you probably should switch away from using flexible array members and just use normal pointers.

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