Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Struct array member without specific length

Tags:

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?

like image 382
FaceBro Avatar asked Jun 19 '13 07:06

FaceBro


People also ask

Why do some structures end with an array of size 1?

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.

What is flexible array member in C?

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.

Can a struct have a member variable that is an array?

A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member.

What is struct hack?

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


2 Answers

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?

like image 155
P.P Avatar answered Sep 18 '22 11:09

P.P


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; } 
like image 33
Medinoc Avatar answered Sep 20 '22 11:09

Medinoc