Geded
Geded

Reputation: 13

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.

Upvotes: 1

Views: 444

Answers (1)

templatetypedef
templatetypedef

Reputation: 372724

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.

Upvotes: 5

Related Questions