2013-02-25 87 views
6

我想創建一個結構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; 
+1

你有沒有嘗試過的東西? – 2013-02-25 13:08:10

回答

5

您可以使用嵌套{}

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; 
+0

謝謝!那樣做了。 – Tomzie 2013-02-25 13:13:01

1

對於一個18歲的李四,居住地址,42

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

你可以請檢閱這個問題。 http://stackoverflow.com/questions/42756562/namespace-or-packages-in-c-modules – 2017-03-13 04:19:16