用里面的struct类型初始化一个struct

时间:2013-02-25 13:02:27

标签: c struct

我想创建一个struct Person,它由两个struct类型和一个变量组成。我怎样才能初始化并使用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;

2 个答案:

答案 0 :(得分:6)

您可以使用嵌套的{}

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;

答案 1 :(得分:1)

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

struct person{
   struct name fullName;
   struct address fullAddress;
   int age;
} person = {{"John", "Doe"}, {"address", 42}, 18};