1

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!

1
  • Sorry was a typing mistake. Also tried with "%s\n" not working. Commented Nov 7, 2020 at 16:47

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.