这种字节对齐的题,字节对齐的原因是什么,这些理论知识绕来绕去的,简单来说,就是一句话,用空间换时间,来提高程序的效率。如果你真想把他彻底搞明白怎么个事,可以去别博主的文章看一看,我这篇文章只有一个目的,那就是,让你快速做对这种题。
首先,我来用学到的比较科学的概念阐述一下怎么做这种题,文章最后是我自己总结的方法
1、确定基本数据类型的自身对齐值(这要是记不住这题就没法玩了,也可以翻一下我写的数据类型的文章哦)
2、自定义类型的自身对齐值(内部成员最大的一个)
3、程序的指定对齐值#pragma pack(n)//n是2的幂次方
4、程序的有效对齐值:较小的一个
5、三个数之和要是最大值的x倍
是不是感觉四条语句全部看得懂,但是放在一起该怎么看呢?先别急,我们看点题:
#include<stdio.h>
/*struct S3
{
double d; //8
char c; //1+3
int i; //4
};
int main()
{
printf("%d\n", sizeof(struct S3));//16
}
/*struct S2
{
char c1;//1+1
char c2;//1+1
int i; //4
};
int main()
{
printf("%d\n", sizeof(struct S2));//8
}
/*struct Test
{
char a;//1+3
int b;//4
char c;//1+3
}Test;
int main()
{
printf("%d\n", sizeof(struct Test));//12
}
怎么样,这三小题有没有难住你?没有,那我们玩点骚的
#include<stdio.h>
typedef struct Test
{
int a; //4+4
struct//8
{
short b; //2+6
double c[10]; //8*10
char d; //1+7
};
short e; //2+6
}Test;
//这种结构体嵌套问题,首先你要从里面的结构体开始看,里面结构体最大值为该结构体类型的大小,数组的话只能看它的类型哦,然后把各个部分相加
void main()
{
printf("size = %d\n", sizeof(Test));//112
}
这题有意思吧,继续来咯
#include<stdio.h>
typedef struct Test
{
int a; //4+4
struct//8
{
double b; //8
int c; //4
char e; //1+3
};
short f; //2+6
}Test;
void main()
{
printf("size = %d\n", sizeof(Test));//32
}
怎么样,上面的都算对了吧
typedef struct Test
{
int a; //4 + 4
struct t
{
double b; //8
int c; //4
char e; //1 + 3
};
short f; //2 + 6
}Test;
void main()
{
printf("size = %d\n", sizeof(Test)); //32
Test t;
}
你是不是也和我一样,算的32,那么不好意思,错了,因为我手滑多打了一个t,所以struct t可不是一个结构体了,而是一个类型,没有大小,也就是可以把它省略,那么Test的大小应该是多少呢?对,8。
再来一个,放心,这个没有陷阱
#include<stdio.h>
typedef struct Test
{
short a; //2 + 6
struct
{
int b; //4 + 4
double c; //8
char d; //1 + 7
};
int e; //4 + 4
}Test;
void main()
{
printf("size = %d\n", sizeof(Test)); //40
}
怎么样,有点感觉了吗,再来一个题
#include<stdio.h>
#pragma pack(1)
typedef struct Test
{
char a; //1
double b; //8
int c; //4
}Test;
void main()
{
printf("size = %d\n", sizeof(Test)); //
}
等于多少,看清楚别上当了
最后一个,如果是联合体呢
#include<stdio.h>
#pragma pack(1)
typedef union Test
{
char a; //1
double b; //8
int c; //4
}Test;
void main()
{
printf("size = %d\n", sizeof(Test)); //不占
}
其实所有的题都差不多,现在也是最后的环节,我把我的方法描述一下
我把它定义为:
内存凑整法
什么意思呢?我画个图你就明白了,我们就拿一个char a;double b;int c;来举例
以上,我认为做对个题至少是手到擒来。