cflexible-array-member

Is there a standard way to statically initialize flexible array members in C?


I need a statically created data structure in memory comprised of a table of string vectors, effectively:

typedef struct {
    char *argv[];
} Entry;

const Entry Table[] = {
    {"a"},
    {"a", "b", "c"}
};

But trying to compile this results in error: initialization of flexible array member in a nested context

Apparently this is possible in GCC, according GCC Manual: 6.18 Arrays of Length Zero. This may be possible following C 2018 6.7.2.1 18, although in regard to that I read elsewhere

There cannot be an array of structures that contain a flexible array member.

Is there a standard way to achieve this behavior? If not, is there a preferred way?


Solution

  • You can't do it with a flexible array member.

    Instead, you can use char **argv and initialize it using compound literals.

    typedef struct {
        char **argv;
    } Entry;
    
    const Entry table[] = {
        { (char *[]) { "a", NULL } },
        { (char *[]) { "a", "b", "c", NULL } }
    };
    

    I added NULL to each of the arrays so the application can tell their lengths (the real argv has this as well).