Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a structure with flexible array member

I have the following structure

typedef struct _person {     int age;     char sex;     char name[]; }person; 

I have done some basic internet search (but unsuccessful) on how to create an instance and initialize a structure with a flexible array member without using malloc().

For example: for normal structures like

struct a {     int age;      int sex; }; 

We can create an instance of struct a and initialize it like

struct a p1 = {10, 'm'}; 

But for structures with flexible array in it (like _person as mentioned above) how can we create an instance and initialize like how we do it for normal structures?

Is it even possible? If so, how do we pass the array size during the initialization and the actual value to be initialized?

(or)

Is it true that the only way to create a structure with flexible array is using malloc() as mentioned in C99 specification - 6.7.2.1 Structure and union specifiers - point #17?!

like image 823
Sangeeth Saravanaraj Avatar asked Dec 31 '11 10:12

Sangeeth Saravanaraj


People also ask

How do you declare a flexible array in C++?

In C99, you can declare a flexible array member of a struct as such: struct blah { int foo[]; };

What is AC flexible array member?

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.

Is it possible to initialize an array of structure explain?

It's called designated initializer which is introduced in C99. It's used to initialize struct or arrays, in this example, struct . Show activity on this post. It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name.


2 Answers

No, flexible arrays must always be allocated manually. But you may use calloc to initialize the flexible part and a compound literal to initialize the fixed part. I'd wrap that in an allocation inline function like this:

typedef struct person {   unsigned age;   char sex;   size_t size;   char name[]; } person;  inline person* alloc_person(int a, char s, size_t n) {   person * ret = calloc(sizeof(person) + n, 1);   if (ret) memcpy(ret,                   &(person const){ .age = a, .sex = s, .size = n},                   sizeof(person));   return ret; } 

Observe that this leaves the check if the allocation succeeded to the caller.

If you don't need a size field as I included it here, a macro would even suffice. Only that it would be not possible to check the return of calloc before doing the memcpy. Under all systems that I programmed so far this will abort relatively nicely. Generally I think that return of malloc is of minor importance, but opinions vary largely on that subject.

This could perhaps (in that special case) give more opportunities to the optimizer to integrate the code in the surroundings:

#define ALLOC_PERSON(A,  S,  N)                                 \ ((person*)memcpy(calloc(sizeof(person) + (N), 1),               \                  &(person const){ .age = (A), .sex = (S) },     \                  sizeof(person))) 

Edit: The case that this could be better than the function is when A and S are compile time constants. In that case the compound literal, since it is const qualified, could be allocated statically and its initialization could be done at compile time. In addition, if several allocations with the same values would appear in the code the compiler would be allowed to realize only one single copy of that compound literal.

like image 180
Jens Gustedt Avatar answered Oct 09 '22 07:10

Jens Gustedt


There are some tricks you can use. It depends on your particular application.

If you want to initialise a single variable, you can define a structure of the correct size:

   struct  {         int age;         char sex;         char name[sizeof("THE_NAME")];     } your_variable = { 55, 'M', "THE_NAME" }; 

The problem is that you have to use pointer casting to interpret the variable as "person"(e.g. "*(person *)(&your_variable)". But you can use a containing union to avoid this:

union {  struct { ..., char name[sizeof("THE_NAME")]; } x;  person p; } your_var = { 55, 'M', "THE_NAME" }; 

so, your_var.p is of type "person". You may also use a macro to define your initializer, so you can write the string only once:

#define INIVAR(x_, age_, sex_ ,s_) \    union {\      struct { ..., char name[sizeof(s_)]; } x;\      person p;\     } x_ = { (age_), (sex_), (s_) }  INIVAR(your_var, 55, 'M', "THE NAME"); 

Another problem is that this trick is not suitable to create an array of "person". The problem with arrays is that all elements must have the same size. In this case it's safer to use a const char * instead of a char[]. Or use the dynamic allocation ;)

like image 33
Giuseppe Guerrini Avatar answered Oct 09 '22 09:10

Giuseppe Guerrini