结构体

1.结构体的声明

#include<stdio.h>
struct stu//声明一个学生类型//想通过学生类型来创建学生变量
{
	char name[20];
	char tele[12];
	char sex[20];
	int age;
}s4, s5, s6;//全局变量
struct stu s3;//全局变量
int main()
{
	struct stu s1 = { 0 };
	struct stu s2 = { 0 };//创建局部变量并初始化
	return 0;
}

2.结构的自引用

#include<stdio.h>
typedef struct Node
{
	int data;//4
	struct Node* next;//指针大小4/8
}Node;//重新命名结构体的名字
int main()
{
	struct Node n1;
	Node n2;
	return 0;
}

3.结构体变量的定义和初始化

#include<stdio.h>
struct T
{
	double weight;
	short age;
};
struct s
{
	struct T stu;
	char c;
	int a;
	double d;
	char arr[20];
};
int main()
{
	struct s s = { {55.6,30},'c',100,3.14,"hello" };
	printf("%lf %c %d %f %s\n",s.stu.weight,s.c, s.a, s.d, s.arr);
	return 0;
}

4.结构体内存对齐

规则:

(1)第一个成员在与结构体变量偏移量为0的地址;

(2)其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处,vs编译器中对齐数默认为8;

(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 s1 = { 0 };
	printf("%d\n", sizeof(s1));
	struct s2 s2 = { 0 };
	printf("%d\n", sizeof(s2));
	return 0;
}

可以修改默认对齐数:

#pragma pack (4) //设置默认对齐数为4

#pragma pack() //取消设置默认对齐数

5.计算偏移量

#include <stdio.h>
#include<stddef.h>
struct s
{
	char c;
	int i;
	double d;
};
int main()
{
	printf("%d\n", offsetof(struct s,c));//头文件是<stddef.h>
	printf("%d\n", offsetof(struct s,i));
	printf("%d\n", offsetof(struct s,d));
	return 0;
}

6.结构体传参

结构体传参的时候要传结构体的地址

7.位段

规则:

(1)位段的成员可以是int,unsigned int,signed int 或者是char 类型;

(2)位段的空间上是按照需要以4个字节(int)或者1个字节(char)来开辟的;

(3)位段涉及很多不确定因素,位段是不跨平台的,注重可移植的程序应该避免使用位段。

#include <stdio.h>
struct s
{
	int a : 2;//2个比特位
	int b : 5;//5个比特位
	int c : 10;//10个比特位
	int d : 30;//30个比特位
};
int main()
{
	struct s s;
	printf("%d\n", sizeof(s));
	return 0;
}

8.枚举(一一列举)

#include <stdio.h>
enum color
{
	RED = 1,
	YELLOW = 3,
	BLUE=6 //赋初始值
};
int main()
{
	enum color c = BLUE;
	printf("%d %d %d\n", RED, YELLOW, BLUE);
	return 0;
}

9.联合(联合体/共用体)

联合的大小至少是最大成员的大小;当最大成员大小不是最大对齐数的整数倍的时候,就要对齐到最大对齐数的整数倍。

#include<stdio.h>
union Un
{
	char c;
	int i;
};
int main()
{
	union Un u;
	printf("%d\n", sizeof(u));
	printf("%p\n", &(u.c));
	printf("%p\n", &(u.i));
	printf("%p\n", &u);
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值