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?
Some Windows structures are variable-sized, beginning with a fixed header, followed by a variable-sized array. When these structures are declared, they often declare an array of size 1 where the variable-sized array should be.
Flexible array members are a special type of array in which the last element of a structure with more than one named member has an incomplete array type; that is, the size of the array is not specified explicitly within the structure.
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member.
“Struct Hack” technique is used to create variable length member in a structure. In the above structure, string length of “name” is not fixed, so we can use “name” as variable length array. Let us see below memory allocation. struct employee *e = malloc(sizeof(*e) + sizeof(char) * 128);
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?
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With