lat3r
lat3r

Reputation: 13

Accessing Element in Array Inside Struct Dynamically Allocated

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);
index++;
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!

Upvotes: 1

Views: 253

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

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("%s\n", 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++)
        free(mystruct->myarray[index]);
    free(mystruct);

Upvotes: 1

Related Questions