Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the real benefits of flexible array member?

After reading some posts related to flexible array member, I am still not fully understand why we need such a feature.

Possible Duplicate:
Flexible array members in C - bad?
Is this a Flexible Array Struct Members in C as well?

(Blame me if I didn't solve my problem from the possible duplicate questions above)

What is the real difference between the following two implementations:

struct h1 {
    size_t len;
    unsigned char *data;
};

struct h2 {
    size_t len;
    unsigned char data[];
};

I know the size of h2 is as if the flexible array member (data) were omitted, that is, sizeof(h2) == sizeof(size_t). And I also know that the flexible array member can only appear as the last element of a structure, so the original implementation can be more flexible in the position of data.

My real problem is that why C99 add this feature? Simply because sizeof(h2) doesn't contain the real size of data? I am sure that I must miss some more important points for this feature. Please point it out for me.

like image 703
Yanzhe Chen Avatar asked Dec 01 '13 08:12

Yanzhe Chen


1 Answers

The two structs in your post don't have the same structure at all. h1 has a integer and a pointer to char. h2 has an integer, and an array of characters inline (number of elements determined at runtime, possibly none).

Said differently, in h2 the character data is inside the struct. In h1 it has to be somewhere outside.

This makes a lot of difference. For instance, if you use h1 you need to take care of allocating/freeing the payload (in addition to the struct itself). With h2, only one allocation/free is necessary, everything is packaged together.

One case where using h2 might make sense is if you're communicating with something that expects messages in the form of {length,data} pairs. You allocate an instance of h2 by requesting sizeof(h2)+how many payload chars you want, fill it up, and then you can transfer the whole thing in a single write (taking care about endianess and such of course). If you had used h1, you'd need two write calls (unless you want to send the memory address of the data, which usually doesn't make any sense).

So this feature exists because it's handy. And various (sometimes non-portable) tricks where used before that to simulate this feature. Adding it to the standard makes sense.

like image 65
Mat Avatar answered Nov 09 '22 02:11

Mat