A. 基本知识
与数组的对比
数组:
构造类型
只能有多个相同类型的数据构成
结构体:
结构体类型
可以由多个不同类型的数据构成
1. 定义类型
1 struct Student
2 {
3 int age;
4 char *name;
5 float height;
6 };
2. 定义结构体变量
定义变量的多种方式
a.
1 //define a struct variable
2 struct Student stu = {27, "simon", 1.65f};
b.
1 struct Student {
2 int age;
3 char *name;
4 float height;
5 } stu = {25, "simon", 1.65f};
1 /*错误写法
2 struct Student p;
3 p = {17, "Tom"};
4 */
c.
1 struct Student p; 2 p.age = 17; 3 p.name = "Tom”;
d.
1 struct Student p2 = {17, "Sam”};
e.
1 struct Student p3 = {.name="Judy", .age= 44};
f.匿名
1 struct
2 {
3 int age;
4 char *name;
5 } stu3;
3. 不允许结构体进行递归定义
在结构体构造代码内定义本结构体的变量
4. 可以包含其他的结构体
1 void test1()
2 {
3 struct Date
4 {
5 int year;
6 int month;
7 int day;
8 };
9
10 struct Student
11 {
12 int age;
13 struct Date birthday;
14 };
15
16 struct Student stu = {25, {1989, 8, 10}};
17
18 printf("my birthday ==> %d-%d-%d
", stu.birthday.year, stu.birthday.month, stu.birthday.day);
19 }
5. 结构体数组
1 struct Student
2 {
3 int age;
4 char *name;
5 float height;
6 } stus[5];
匿名
1 struct
2 {
3 int age;
4 char *name;
5 float height;
6 } stus[5];
6. 结构体作为函数参数, 传递的仅仅是成员的值
7. 指向结构体的指针
1 void test4()
2 {
3 struct Person p = {33, "ss"};
4 struct Person *pointer;
5
6 pointer = &p;
7
8 printf("test4: person's age = %d
", p.age);//It's p!!!, not pointer!!
9 printf("test4: person's age = %d
", (*pointer).age);
10 printf("test4: person's age = %d
", pointer->age);
11 }
==> 3种方式访问结构体成员变量
a. struct.v
b. (*pointer).v
c. pointer->v
8.结构体内存分配
a.定义的时候不会分配存储空间
b.定义结构体变量的时候分配空间,分配的空间大小是最大成员变量的倍数
9.结构体复制
1 struct Student p2 = {17, "Sam"};
2 struct Student p3 = {.name="Judy", .age= 44};
3 p3 = p2;
4 printf("p3: age->%d, name-.%s
", p3.age, p3.name);
out:
p3: age->17, name->.Sam
