How to include a dynamic array INSIDE a struct in C?

The way you have it written now , used to be called the “struct hack”, until C99 blessed it as a “flexible array member”. The reason you’re getting an error (probably anyway) is that it needs to be followed by a semicolon:

#include <stdlib.h>

struct my_struct {
    int n;
    char s[];
};

When you allocate space for this, you want to allocate the size of the struct plus the amount of space you want for the array:

struct my_struct *s = malloc(sizeof(struct my_struct) + 50);

In this case, the flexible array member is an array of char, and sizeof(char)==1, so you don’t need to multiply by its size, but just like any other malloc you’d need to if it was an array of some other type:

struct dyn_array { 
    int size;
    int data[];
};

struct dyn_array* my_array = malloc(sizeof(struct dyn_array) + 100 * sizeof(int));

Edit: This gives a different result from changing the member to a pointer. In that case, you (normally) need two separate allocations, one for the struct itself, and one for the “extra” data to be pointed to by the pointer. Using a flexible array member you can allocate all the data in a single block.

Leave a Comment