C语言 使用内部结构类型初始化结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15067620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize a struct with struct types inside
提问by Tomzie
I would like to create a struct Person, which consists of two struct types and a variable inside. How can I initialize and use the struct Person then?
我想创建一个结构体 Person,它由两个结构体类型和一个内部变量组成。那么如何初始化和使用结构人呢?
struct name{
char *firstName;
char *lastName;
} name;
struct address{
char *street;
int number;
} address;
struct person{
struct name fullName;
struct address fullAddress;
int age;
} person;
采纳答案by md5
You can use nested {}.
您可以使用嵌套的{}.
struct person
{
struct name fullName;
struct address fullAddress;
int age;
} person =
{
{
"First Name", /* person.fullName.firstName */
"Last Name", /* person.fullName.lastName */
},
{
"Street", /* person.fullAddress.street */
42 /* person.fullAddress.number */
},
42 /* person.age */
};
Then you can access to the other members as follow:
然后您可以按如下方式访问其他成员:
person.fullName.firstName;
person.fullName.lastName;
person.fullAddress.street;
person.fullAddress.number;
person.age;
回答by pmg
For a 18-year-old John Doe, living at address, 42
对于住在地址 42 岁的 18 岁的 John Doe
struct person{
struct name fullName;
struct address fullAddress;
int age;
} person = {{"John", "Doe"}, {"address", 42}, 18};

