1

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Geded
  • 13
  • 2
  • 1
    what error do you get? – Assem Jan 16 '16 at 01:14
  • "Invalid use of flexible array member" – Geded Jan 16 '16 at 01:15
  • see this http://stackoverflow.com/questions/28718198/how-to-access-array-of-flexible-arrays-in-cache-friendly-manner – zangw Jan 16 '16 at 01:19
  • Note that you will need to know how many entries are allocated to the FAM somehow. I suppose you could allocate an extra pointer and mark that as null, but you do have to allocate the space for the `c` test case pointers when you allocate the base structure. It's the only way it can be made to work. – Jonathan Leffler Jan 16 '16 at 01:24
  • SO 28718198 is related (and probably worth a read), but it is not a duplicate of this. – Jonathan Leffler Jan 16 '16 at 01:27

1 Answers1

5

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.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065