Search code examples
arrayscpointersstructmember

flexible array size within typedef for const struct member


I would like to use C-code for a struct type having a member of type pointer to a flexible sized array. But the access to the array elements fails when the array-size is not specified in the type declaration. Using malloc() is not an option, since the arrays should be global constants. Furthermore the struct "instances" should refer to each other, what is not covered by the example, because this already works. Am I either not using the correct syntax for the element-access or the member-declaration?

void up(void){
    typedef struct _sType{
        const char name[6];
        const struct _sType* (*sub)[]; // replace (*sub)[] here by (*sub)[3] for correct element access
    }sType;

    const sType s1 = {
        "S1",
        NULL,
    };

    const sType s2 = {
        "S2",
        NULL,
    };

    const sType* items[] = {
        &s1,
        &s2,
        NULL
    };

    const sType s0 = {
        "S0",
        &items
    };

    const char* dbg = s0.name; // just use s0 once for not optimizing it away 
}

I monitored the memory. The addresses and values of items and s0->sub do not differ regardless if the struct-member is defined flexible or fixed. I access the elements for example by &items[0]->name and s0->sub[0]->name


Solution

  • sub is not a VLA, but a pointer to an incomplete array type. In order to use it, you would need to convert it to a pointer to a complete array type.

    For example:

    const sType *(*arr)[2] = s0.sub;
    printf("%s\n", (*arr)[0]->name);
    printf("%s\n", (*arr)[1]->name);
    

    This prints:

    S1
    S2