26

I have encountered this piece of code:

struct test                   
{                                        
 uint32       num_fields;            
 char array_field [];               
}; 

How can I understand array_field? Is this a gcc extension for the C language?

1
  • 2
    Please revert the update and post a new question. Commented Jun 19, 2013 at 8:49

2 Answers 2

24

It's a C99 feature, called flexible array member which is typically used to create a variable length array.

It can only be specified as the last member of a struct without specifying the size (as in array_field [];).


For example, you can do the following and the member arr will have 5 bytes allocated for it:

struct flexi_example
{
int data;
char arr[];
};


struct flexi_example *obj;

obj = malloc(sizeof (struct flexi_example) + 5);

Its pros/cons discussed here:

Flexible array members in C - bad?

Sign up to request clarification or add additional context in comments.

10 Comments

Any idea why this was added to C instead of just using pointers? I hardly see why to use arrays at all except to allocate some pre-determined space on the stack. This doesn't give you that benefit.
I finally got the point when I printf the sizeof of the struct. Actually, the array_field does not occupy any bytes, it's the same thing as array_field[0], which is used to create a variable length array in gcc.
@xaxxon It's added because with this feature, you can have true VLAs inside a struct, and you don't have to mallocate memory twice. This increases readability and decreases memory fragmentation and the number of pointer traversals (and thus perhaps boosts performance a little bit).
@H2CO3: Flexible array members are not VLAs. In particular, sizeof applied to the struct doesn't include the size of the array member; you just have to keep track of that yourself.
The flexible array member was added to formalize the long existing and relied upon "struct hack" (that search really isn't complete, as some instances are left off, but without the quotes a lot of junk creeps in).
|
3

Such structures are usually allocated on the heap with a calculated size, with code such as the following:

#include <stddef.h>

struct test * test_new(uint32 num_fields)
{
    size_t sizeBeforeArray = offsetof(struct test, array_field);
    size_t sizeOfArray = num_fields * sizeof(char);
    struct test * ret = malloc(sizeBeforeArray + sizeOfArray);
    if(NULL != ret)
    {
        ret->num_fields = num_fields;
    }
    return ret;
}

Comments

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.