C语言之结构体(二)

  1. 结构体对齐补齐
  2. 位段
c 复制代码
// 
// 结构体对齐补齐
// 结构体的大小一定是4的倍数。
// 如果成员变量大小加起来不足4的倍数 补齐。
// 为什么这样,是因为有对齐原则
// 如果是比较大的成员  首地址必须是4的倍数
// 如果是比较小的成员  可以几个凑成4.
//
struct A {
	char c;
	int i;
	double d;
};
void test8()
{
	struct A a;
	printf("%d", sizeof(a));
}

// 位段
// 有时候用不到特别大的内存 ,可以用位段来节约内存
// 例如:需要32个bit位  用结构体最少是32个字节
//
void test9()
{
	struct f {
		unsigned bit1 : 1;
		unsigned bit2 : 2;
		unsigned bit3 : 3;
	};
	struct f f1 = { 9,9,9 };
	printf("%d,%d,%d\n", f1.bit1, f1.bit2, f1.bit3);
	printf("\n%d\n", sizeof(f1));
}
  1. 案例
c 复制代码
void test10()
{
	typedef struct Student
	{
		char name[20];
		int age;
		double score;
	} Student;
	int n;
	printf("请输入学生数:");
	scanf("%d", &n);
	Student* p = malloc(sizeof(Student) * n);
	if (NULL == p)
	{
		printf("申请内存失败\n");
		return -1;
	}
	double count = 0;
	for (int i = 0; i < n; i++)
	{
		printf("请输入第%d个同学的姓名:", i + 1);
		scanf("%s", (p + i)->name);
		printf("请输入第%d个同学的年龄:", i + 1);
		scanf("%d", &(p + i)->age);
		printf("请输入第%d个同学的成绩:", i + 1);
		scanf("%lf", &(p + i)->score);
		count += (p + i)->score;
	}
	printf("总分:%g,平均分:%g\n", count, count / n);

}
相关推荐
沐晓时光1 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
信奥卷王1 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵1 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
SuperByteMaster3 小时前
wfi进入之前没有清除basepri, 导致中断优先级不够,wfi 退不出来
c语言
徐小黑ACG3 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
码完就睡3 小时前
数据结构——红黑树
数据结构
码爸3 小时前
数据结构详细介绍
数据结构
Navigator_Z3 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛4 小时前
cpp学习笔记--常量指针
java·开发语言·算法