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