[英]Using designated initializers for initializing a 2D char array initializer in a struct emits an error C2078 in VS2013
I'm using VS2013. 我正在使用VS2013。 The whole program is C, not C++.
整个程序是C,而不是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". 我收到“错误C2078:初始化程序太多”。 This is because of the array initialization- If I remove the
.titles = { ...
line, the error goes away. 这是因为数组初始化 - 如果我删除
.titles = { ...
行,则错误消失。 Why am I getting this error? 为什么我收到此错误? Is there a different way to accomplish this type of string initialization within a struct initializer?
在struct初始化程序中是否有不同的方法来完成这种类型的字符串初始化?
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.
代码库的其他部分要求此结构的大小正好是400字节。
Further, I'm quite aware that I could use strcpy
to fill in each field, but that does not answer my question. 此外,我非常清楚我可以使用
strcpy
来填充每个字段,但这并不能回答我的问题。
In C, it's easier to do this: 在C中,这样做更容易:
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?
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.