Lance Pollard
Lance Pollard

Reputation: 79178

How to create struct with dynamically sized array in it in C

Given I have a struct something like this:

struct arr {
  int len;
  void *item[]; // still playing with this
};

typedef struct arr my_array;

I'm wondering how you initialize it.

my_array foo = { 0, 1000 }; // 1000 spaces reserved.
// or perhaps...
my_array foo = { 0, [1000] };

Because when you have a regular array, you specify the size like this:

int anarray[1000];

So I was thinking you could do that to initialize the pointer value in the array struct above.

Maybe even

foo->item[1000];

I don't know. Wondering if anything like that is possible.

Upvotes: 3

Views: 122

Answers (2)

John Bode
John Bode

Reputation: 123458

A struct type with a flexible array member needs to be allocated dynamically if you want the array to have any space allocated to it:

struct arr *foo = malloc( sizeof *foo + (sizeof foo->item[0] * 1000) );
if ( foo )
{
  foo->len = 1000;
  for ( int i = 0; i < foo->len; i++ )
    foo->item[i] = some_value();
}
...
free( foo );

Upvotes: 2

Flexible array members are only really useful when the structure is dynamically allocated. If the structure is allocated statically or automatically (i.e. on the stack), the amount of memory allocated is sizeof(struct arr) which is calculated with 0 members in item. There is no syntax to define a variable whose type is a structure with a flexible array member and specify the size of that array.

So if you allocate this structure on the stack, that's all there is to it:

struct my_array foo = { 0 };

To put elements in the flexible array, you need to allocate the memory dynamically.

struct my_array *foo = malloc(sizeof(*foo) + 1000 * sizeof(foo->item[0]));

Upvotes: 3

Related Questions