定义一个结构体
struct Company {
char *name;
char *id;
char *location;
}
初始化
1 struct Company company = {.name="imooc", .id="1212121"};
怎么省略struct呢 声明的时候可以这么声明,然后就可以直接用Company 这个关键字来定义company了
1 typedef struct Company { 2 char *name; 3 char *id; 4 char *location; 5 } Company;
typeof 可以简化类型的输入
结构体内部引用另一个结构体
1 typedef struct Company { 2 char *name; 3 char *id; 4 char *location; 5 } Company; 6 7 typedef struct Person { 8 char *name; 9 int age; 10 char *id; 11 Company *company; 12 Company company2; 13 struct { 14 int extra; 15 char *extra_str; 16 } extra_value; 17 struct Person *partner; 18 } Person; 19 20 struct Company company = {.name="imooc", .id="1212121"}; 21 struct Person person = {.name="bennyhuo", .id="12113322222", .company=&company, 22 .company2={.name="imooc", .id="32323232"} 23 };View Code
全部代码
1 #include <stdio.h> 2 #include <io_utils.h> 3 4 int main() { 5 /* 6 * struct <结构体名> { 7 * <成员类型> <成员名>; 8 * ... 9 * } <结构体变量>; 10 */ 11 12 typedef struct Company { 13 char *name; 14 char *id; 15 char *location; 16 } Company; 17 18 typedef struct Person { 19 char *name; 20 int age; 21 char *id; 22 Company *company; 23 Company company2; 24 struct { 25 int extra; 26 char *extra_str; 27 } extra_value; 28 struct Person *partner; 29 } Person; 30 31 struct Company company = {.name="imooc", .id="1212121"}; 32 struct Person person = {.name="bennyhuo", .id="12113322222", .company=&company, 33 .company2={.name="imooc", .id="32323232"} 34 }; 35 36 PRINT_INT(person.age); 37 person.age = 30; 38 39 //person.company->name 40 //person.extra_value.extra 41 42 PRINT_HEX(&person); 43 44 Person *person_ptr = &person; 45 46 puts(person_ptr->name); 47 48 PRINT_INT(sizeof(Person)); 49 PRINT_INT(sizeof(person)); 50 51 struct { 52 char *name; 53 int age; 54 char *id; 55 } anonymous_person; 56 57 Person person1 = {.name = "andy", .age = 20}; 58 PRINT_INT(person1.age); 59 60 return 0; 61 }View Code
执行结果
标签:char,struct,Company,name,学习,person,C语言,id,结构 From: https://www.cnblogs.com/liumy/p/17092815.html