Accessing Element in Array Inside Struct Dynamically Allocated

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Accessing Element in Array Inside Struct Dynamically Allocated on this date .

So I have an array of structs with every struct containing a dynamic array of strings.

typedef struct _test {
    int total;
    char *myarray[];
} Test;

This how I allocated enough memory

Test *mystruct = (Test *)malloc(size);

Above is how my struct is formated

mystruct[x].myarray[index] = strdup(name);
mystruct[x].total = index;

when trying to access a string in that array i.e. :

printf("%s", mystruct[0].myarray[0]);

Nothing prints, thanks for any help!


The following is correct. I’ll explain below.

typedef struct TEST {
    int total;
    char *myarray[];
} Test;

int StackOveflowTest(void)
    int index;
    Test *mystruct = malloc(sizeof(Test)+10*sizeof(char *));

    for (index=0; index<10; index++)
        mystruct->myarray[index] = strdup("hello world");
    mystruct->total = index;

    for (index=0; index<10; index++)
        printf("%sn", mystruct->myarray[index]);

    return 0;

Actually, you declare an “array of pointers” myarray, however that array has zero elements. This “trick” is used to have the ability that at the end of the struct you have an array of variable size when malloc‘ing the array:

Test *mystruct = malloc(sizeof(Test)+10*sizeof(char *));

This allocates the size of the struct and adds room for 10 array elements.

Since you did not allocate this flexible part of the struct, you wrote into “nothing” and are lucky the program did not abort (or it did, which is why there was no output).

P.s.: don’t forget to free the memory when you are done:

    for (index=0; index<10; index++)