arrayscinitializationdeclarationcompound-literals

Can I declare an array of different length arrays in C without variable names?


I am trying to figure out if it's possible to do the following, but without having to declare the individual variables...

static char *set_list1[] = { "set", "one", NULL };
static char *set_list2[] = { "set", "one", "negative", NULL };
static char *set_list3[] = { "set", NULL };
static char *set_list4[] = { "set", "one", "new", "item", "here", NULL };
static char **set_list[] = { set_list1, set_list2, set_list3, set_list4, NULL };

Basically I need an array of pointers, each pointer then points to a variable length array of strings (which happen to be terminated with a NULL pointer.

Obviously I can declare it like the above, but is there a way to do this without having to declare each one with a name?

Intuitively this feels like it should work, but doesn't...

static char **my_array[] = {
    { "one", "two", NULL },
    { "another", NULL },
    { "more", "items", "here", NULL },
    NULL
};

Any help appreciated


Solution

  • For example in C23 you may use compound literals like

    static char **my_array[] = {
        ( static char * [] ){ "one", "two", NULL },
        ( static char * [] ){ "another", NULL },
        ( static char * [] ){ "more", "items", "here", NULL },
        NULL
    };
    

    Or the same declaration but without the storage class specifier static

    static char **my_array[] = {
        ( char * [] ){ "one", "two", NULL },
        ( char * [] ){ "another", NULL },
        ( char * [] ){ "more", "items", "here", NULL },
        NULL
    };