一、结构体是什么?
结构体指的是一种数据结构,结构体可以被声明为变量、指针或数组等,用以实现较复杂的数据结构。结构体同时也是一些元素的集合,这些元素称为结构体的成员且这些成员可以为不同的类型,成员一般用名字访问 。
二、使用步骤
1.结构体定义
#include <stdio.h>
struct tag //结构体标签
{
int age;
char name; //结构体成员
double value;
}s1; //定义结构体变量
//未定义结构体标签的结构体,定义了结构体变量S2不能重复创建变量
struct
{
int age;
char name; //结构体成员
double value;
}s2; //结构体变量
//未定义结构体变量的结构体
struct tag
{
int age;
char name; //结构体成员
double value;
};
struct tag t1,t2,t3; // 用标签生命变量
//使用typedef创建新类型
typedef struct
{
int age;
char name; //结构体成员
double value;
} student;
student a1,a2,a3; //使用typedef定义的新类型声明变量
int main()
{
struct tag s1 = {12,'a',123.123}; //结构体变量初始化
return 0;
}
2.结构体指针
#include <stdio.h>
struct tag //结构体标签
{
int age;
char name; //结构体成员
double value;
}s1={12,'a',123.123};
int main()
{
struct tag *p; //定义结构体指针变量p
p=&s1;
printf("%d\n",p->age); //指针访问结构体成员变量
printf("%c\n",p->name);
printf("%.3f\n",p->value);
}
3.结构体自调用(链表)
#include <stdio.h>
struct tag //结构体标签
{
int age;
char name; //结构体成员
struct tag* next;
}s1,s2,s3,s4;
struct tag s1={12,'a',&s2};
struct tag s2={13,'b',&s3};
struct tag s3={14,'c',&s4};
struct tag s4={15,'d',NULL};
int main()
{
struct tag *p; //定义结构体指针变量p
p=&s1;
while(p!=NULL)
{
printf("%d\n",p->age); //指针访问结构体成员变量
p= p->next; //
}
return 0;
}
4.结构体内存对齐
结构体成员变量在内存块中的存放不是连续的,而是有规则的进行对齐排列
结构体内存对齐规则:
1. 第一个成员在与结构体变量偏移量为0的地址处。
2. 其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处。
对齐数 = 编译器默认的一个对齐数 与 该成员大小的较小值。
3. 结构体总大小为最大对齐数(每个成员变量都有一个对齐数)的整数倍。
4. 如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最大对齐数的整数倍处,结构体的整
体大小就是所有最大对齐数(含嵌套结构体的对齐数)的整数倍。
#include <stdio.h>
struct s1
{
char c1;
int a;
char c2;
};
struct s2
{
char c1;
char c2;
int a;
};
int main()
{
struct s1 K1={0};
printf("%d\n",sizeof(K1));
struct s2 K2={ 0 };
printf("%d\n",sizeof(K2));
return 0;
}
/*[Running] cd "f:\c code\" && gcc test1.c -o test1 && "f:\c code\"test1
12
8
[Done] exited with code=0 in 0.552 seconds*/