我正在学习C中的嵌套结构,我想要做的是能够为我的struct的成员结构赋值.我无法搞清楚这一点,我不想强迫自己在结构初始化中初始化成员结构.当我尝试编译此代码时,为什么一直出现错误?
main.c: In function 'main':
main.c:16:23: error: expected expression before '{' token
fooPerson.fullname = {"Foo", 'B', "Baz"};
Run Code Online (Sandbox Code Playgroud)
#define LEN 20
struct names {
char first[LEN];
char middle;
char last[LEN];
};
struct person {
struct names fullname;
};
int main() {
struct person fooPerson;
fooPerson.fullname = {"Foo", 'B', "Baz"};
// NOT this: it works, but not the solution I'm asking for
// struct person fooPerson = {{"Foo", 'B', "Baz"}};
}
Run Code Online (Sandbox Code Playgroud)
从C99开始,您可以使用复合文字:
fooPerson.fullname = (struct names){ "Foo", 'B', "Baz" };
Run Code Online (Sandbox Code Playgroud)
但是,如果你坚持使用C89,那么你大部分都不走运,除非你想做这样的事情:
{
struct names n = { "Foo", 'B', "Baz" };
fooPerson.fullname = n;
}
Run Code Online (Sandbox Code Playgroud)
Felix在评论中指出,这些都不是真正的初始化 - 当它作为声明的一部分发生时,它只是初始化,这不是这里的情况.相反,两者都是作业.不过,这应该做你想要的.