Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using designated initializers for initializing a 2D char array initializer in a struct emits an error C2078 in VS2013

I'm using VS2013. The whole program is C, not C++.

I can initialize an "array of strings" like this without any problems:

char titles[4][80] = { "Dad", "Idiot", "Donut Lover", "Fewl" }; // OK!

I have a struct declared like this:

typedef struct
{
    char name[80];
    char titles[4][80];
} Dude;

When I try to initialize the struct like this:

Dude homer =
{
    .name = "Homer",
    .titles = { "Dad", "Idiot", "Donut Lover", "Fewl" } // error?
};

I get an "error C2078: too many initializers". This is because of the array initialization- If I remove the .titles = { ... line, the error goes away. Why am I getting this error? Is there a different way to accomplish this type of string initialization within a struct initializer?

If I change the declaration of the struct to look like this

typedef struct
{
    char name[80];
    char *titles[4];
} Dude;

the error goes away. This is, however, not a change I can make. Other parts of the code base require that the size of this struct is exactly 400 bytes.

Further, I'm quite aware that I could use strcpy to fill in each field, but that does not answer my question.

like image 784
Veldaeven Avatar asked Nov 21 '22 13:11

Veldaeven


1 Answers

In C, it's easier to do this:

Dude homer =
{
    "Homer",
    { "Dad", "Idiot", "Donut Lover", "Fewl" } // error?
};

Don't know if this works, but you can try:

Dude homer =
{
    .name = "Homer",
    .titles[] = { "Dad", "Idiot", "Donut Lover", "Fewl" } // error?
};
like image 132
Bing Bang Avatar answered May 13 '23 04:05

Bing Bang