2013-02-25 43 views
6

Tôi muốn tạo một cấu trúc Person, bao gồm hai kiểu struct và một biến bên trong. Làm thế nào tôi có thể khởi tạo và sử dụng struct người sau đó?Khởi tạo một cấu trúc với các kiểu cấu trúc bên trong

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

Các bạn đã thử một cái gì đó ? –

Trả lời

5

Bạn có thể sử dụng lồng nhau {}.

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

Sau đó, bạn có thể truy cập đến các thành viên khác như sau:

person.fullName.firstName; 
person.fullName.lastName; 
person.fullAddress.street; 
person.fullAddress.number; 
person.age; 
+0

Cảm ơn! Điều đó đã làm điều đó. – Tomzie

1

Đối với một John Doe 18 tuổi, sống tại địa chỉ, 42

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

bạn có thể vui lòng xem lại câu hỏi này không. http://stackoverflow.com/questions/42756562/namespace-or-packages-in-c-modules –

Các vấn đề liên quan