12

我想创建一个结构 Person,它由两个结构类型和一个变量组成。那么我该如何初始化和使用 struct 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;
4

2 回答 2

9

您可以使用嵌套{}的 .

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 */
};

然后您可以访问其他成员,如下所示:

person.fullName.firstName;
person.fullName.lastName;
person.fullAddress.street;
person.fullAddress.number;
person.age;
于 2013-02-25T13:08:28.003 回答
1

对于住在地址的 18 岁的 John Doe,42

struct person{
   struct name fullName;
   struct address fullAddress;
   int age;
} person = {{"John", "Doe"}, {"address", 42}, 18};
于 2013-02-25T13:09:30.043 回答