3

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.

4
  • Not on the question, but maybe relevant for title: Usually one use {size_t len; type_x item[1];} and then create/expand the array (GNU GCC allows you to use item[0] which could simplify some calculation. Commented Mar 19, 2019 at 16:34
  • alloc/realloc will give it a size Commented Mar 19, 2019 at 16:38
  • 1
    @GiacomoCatenazzi “Usually”? No, not these days. That was the way you had to do it in C89, but C99 introduced the feature that Lance is using, which is called flexible array members. Commented Mar 19, 2019 at 16:43
  • @Gilles, yes, flexible array is the new way. But my point is not to use the second redirection. Commented Mar 19, 2019 at 17:08

2 Answers 2

3

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]));
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

What I like about sizeof is that it allows you to write expressions that seems mind boggling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.