36

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?!

Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
  • 1
    you can't, struct must have compile time size. – Anycorn Dec 31 '11 at 10:48
  • 8
    @Anycorn: structures with flexible array members do have a compile time size. – CB Bailey Dec 31 '11 at 10:56
  • 4
    GCC has an extension that allows you to do something like `struct { size_t len; int data[]; } x = { 4, { 1, 2, 3, 4 } };` and it'll work, but it's not portable. You could always look into your platform's version of `alloca` for a possibly more portable solution, but you'd have to ensure they all behave the same way and have the same implementation quirks. – Chris Lutz Dec 31 '11 at 10:58
  • @Charles not in the sense poster means - there gotta be some sort of malloc or equivalent. – Anycorn Dec 31 '11 at 11:30
  • @ChrisLutz What is the name of the extension and how do I use it? suggestions/pointers please! Thanks! – Sangeeth Saravanaraj Dec 31 '11 at 11:39
  • 2
    http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Zero-Length.html It appears to be on by default (assuming you're not using `-ansi` or anything that would disable it). – Chris Lutz Dec 31 '11 at 12:22
  • If anyone wants to know more about the GCC extension, there is also a dedicated question for it here on SO: [Why does static initialization of flexible array member work?](https://stackoverflow.com/questions/27852062/) – RobertS supports Monica Cellio Jul 09 '20 at 13:47

3 Answers3

14

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.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • 3
    Doing an unchecked copy of the result of `calloc()` is dangerous; if the allocation fails, you get a core dump (or other undefined behaviour which is unlikely to be what you wanted). – Jonathan Leffler Dec 31 '11 at 16:11
  • @JonathanLeffler, right, will modify. I'll integrate that in the function. For the marcro I'll just refer to my generic rant about checking the return of `malloc`. – Jens Gustedt Dec 31 '11 at 16:31
  • Your inline function solution is great. The macro doesn't have any advantage over it, IMHO. It's unreadable, doesn't check calloc return value, and won't perform better. Macros don't generally perform better than inline functions (sometimes worse - consider passing strlen() to a macro, which evaluates it twice). – ugoren Dec 31 '11 at 17:38
  • @ugoren, `const` qualified compound literals are special with respect to optimization. There is more optimization allowed with them, please see my edit. One could probably try to combine both approaches by having a function that does something like `calloc_and_copy_or_fail`. – Jens Gustedt Dec 31 '11 at 17:52
  • 1
    Nice. BTW, instead of `person *ret = calloc(sizeof(person) + n, 1);`, a safer habit to be in is to write `person *ret = calloc(sizeof(*ret) + (sizeof(ret->name[0]) * n), 1);`. – Todd Lehman Jul 11 '15 at 06:34
  • You cover the example if OP wants to initialize the *flexible array member* (FAM) to `0` But how can one initialize the FAM with any other individual element values or as in this case (as `name` suppose to hold a string) a string? I guess this is what OP really meant as he said to initialize the FAM. – RobertS supports Monica Cellio Jul 09 '20 at 13:44
  • Also: Is it possible that one can set the FAM size only by its initializer list? Like it is possible at arrays of unknown size outside of a structure, for example: `int a[] = {1,2,3,4,5};`. – RobertS supports Monica Cellio Jul 09 '20 at 13:44
7

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

Giuseppe Guerrini
  • 4,274
  • 17
  • 32
6

A structure type with a flexible array member can be treated as if the flexible array member were omitted, so you can initialize the structure like this.

person p = { 10, 'x' };

However, there are no members of the flexible array allocated and any attempt to access a member of the flexible array or form a pointer to one beyond its end is invalid. The only way to create an instance of a structure with a flexible array member which actually has elements in this array is to dynamically allocate memory for it, for example with malloc.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • 4
    There's a GCC extension that lets you specify the flexible array member using that same syntax, if that's what you're into. – Chris Lutz Dec 31 '11 at 10:59