Search code examples
c

Are multiple variable-length arrays in a structure in C possible?


Is something like this possible in C? It would be really nice to have both of these.

    typedef struct {
        int r;
        char a0[0];
        char a1[0];
    }


Solution

  • No. Rather use dynamically allocated memory. Something like:

    typedef struct {
        int *data1;
        size_t len1
    
        int *data;
        size_t len2;
    } sometype;
    
    sometype *alloc_sometype(size_t len1, size_t len2) {
        sometype *n = malloc(sizeof(sometype));
    
        if (!n) return NULL;
    
        n->len1 = len1;
        n->len2 = len2;
    
        n->data1 = malloc(sizeof(int) * len1);
        n->data2 = malloc(sizeof(int) * len2);
    
        // Error handling if those malloc calls fail
    
        return n;
    }