标签:amp color date 结构 name div blog logs har
1、结构体的3种定义方式
定义结构体类型后定义结构体变量 //定义结构体类型 struct struct_1{ char *name; int age; }; //结构体大括号外加;每项后加; //定义结构体变量 struct struct_1 str_1 = {"jiao", 26}; str_1.name = "fftu"; //修改函数体中的属性 printf("%s--%d", str_1.name, str_1.age); *结构体实例化后不能重新整体赋值,只能调用属性赋值
定义结构体类型的同时定义结构体变量 struct struct_2{ char *name; int age; } stu_2 = {"heinrich", 88}; struct struct_2 stu_3 = {"jiao", 90}; 直接定义结构体变量 struct{ char *name; int age; } stu_2 = {"heinrich", 88}; 2、结构体中包含结构体 struct info{ char *ps; char *date; }; struct man{ char *name; int age; struct info mans_info; }; struct info info_1 = { "ps_1", "2017.4.1" }; struct man man_1 = {"fftu", 26, info_1}; printf("%s\n%d\n%s\n%s\n", man_1.name, man_1.age, man_1.mans_info.ps, man_1.mans_info.date); 3、结构体数组 struct struct_1{ char *name; int age; }; struct struct_1 str[2] = { {"fftu", 99}, {"jiao", 26} }; printf("%s\n%d", str[1].name, str[1].age); 4、结构体作为参数传递 struct struct_1{ char *name; int age; }; void fun_1(struct struct_1 str){ //struct struct_1相当于类型,比如int str.name = "heinrich"; str.age = 999; } struct struct_1 str_1 = {"jiao", 256}; fun_1(str_1); //传递的是值,原结构体变量不会被修改 printf("%s\n%d", str_1.name, str_1.age); 5、结构体指针 struct struct_1{ char *name; int age; }; void fun_1(struct struct_1 *str){ str->name = "heinrich"; //通过地址访问变量,不做取值运算 str->age = 999; } struct struct_1 str_1 = {"jiao", 256}; struct struct_1 *p = &str_1; fun_1(p); printf("%s\n%d", str_1.name, str_1.age);
标签:amp color date 结构 name div blog logs har
原文地址:http://www.cnblogs.com/jiaoxuanwen/p/6667535.html