包括结构体的基本知识、结构体的内存对齐原理、结构体嵌套和结构体指针
#include <stdio.h>
#include <string.h>
// struct 是一个C语言的一个关键字,用来声明一个结构体类型
// 声明了一个名字叫 student 的结构体类型
// 有两个成员,分别是整型的 id(学号) 字符数组 name(名字)
// struct 只是声明了这样一种数据类型,和普通的数据类型比如int、char
// 一样本身是没有分配空间的,只有在定义变量的时候才会为变量分配空间
struct student
{
int id;
char name[20];
}; //用struct 声明类型的时候要有 ;号,和函数相区分
#if 0
// 变量定义2:直接在结构类型声明的时候定义变量
struct teacher
{
int id;
char name[20];
}t1,t2; // 定义了两个老师的变量 变量名叫 t1、t2
// 变量定义3:结构类型可以不要名字,也就是说不能在其他地方使用了
// 只能在类型声明的时候定义变量
struct
{
int a;
int b;
}a, b; // 定义结构体变量a和b
//
int main()
{
// 结构体的变量定义
// 定义了一个student结构体变量 变量名叫 stu
// 用结构体定义变量的时候,类型要写完整,struct 关键字不能丢
// student stu2; struct 不能丢
struct student stu;
return 0;
}
#endif
// 结构体变量的初始化和成员使用
int main1()
{
// 定义结构体变量并且初始化
struct student stu = {1234, "xiaoming"};
struct student stu2 = {.name="xiaohong", .id=1234};
// 结构的成员变量的使用,结构变量使用成员变量,需要点 . 指明使用的是哪一个成员
printf ("id = %d, name = %s\n", stu.id, stu.name);
}
int main()
{
struct student stu;
// 结构体变量使用
stu.id = 1224;
strcpy(stu.name, "hello");
printf ("id = %d, name = %s\n", stu.id, stu.name);
}
#include <stdio.h>
struct A
{
char ch1;
char ch2;
};
struct B
{
int a;
int b;
};
int main()
{
printf ("%d\n", sizeof(struct A));
printf ("%d\n", sizeof(struct B));
return 0;
}
#include <stdio.h>
struct A
{
char ch;
int a;
};
struct B
{
char ch;
struct A a;
};
int main()
{
printf ("%d\n", sizeof(struct B));
return 0;
}
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
};
int main1()
{
// 定义了一个结构体变量
// 结构体变量名和数组名进行区分
// 数组名代表数组首个元素的地址
// 结构体变量是一个变量不是地址
struct student stu;
// 定义了一个结构体变量指针
struct student *p = &stu;
// 通过指针使用结构体变量:需要新的运算符->
// ->只是用在结构体指针变量引用成员变量的时候
p->id = 10; // stu.id = 10;
strcpy(p->name, "abcd");
printf ("id = %d, name = %s\n", p->id, p->name);
return 0;
}
void printA(struct student a)
{
a.id = 5678;
printf ("id = %d, name = %s\n", a.id, a.name);
}
void printB(struct student *a)
{
a->id = 5678;
printf ("id = %d, name = %s\n", a->id, a->name);
}
int main()
{
struct student a = {1234, "hello"};
struct student b;
b = a;// 结构体变量之间可以直接赋值
// 结构体变量之间可以直接赋值导致结构变量可以直接作为函数参数进行传递
printB(&b);
printf ("id = %d, name = %s\n", b.id, b.name);
return 0;
}