【发布时间】:2020-05-20 05:58:48
【问题描述】:
我已经提到了this question,但仍然无法找到以下案例的答案。
为什么填充不适用于test1的情况?
#include <stdio.h>
typedef unsigned short u16;
typedef unsigned char u8;
typedef struct
{
u8 a[5];
u8 b;
u8 c;
} test1;
typedef struct
{
u8 a[5];
u16 b;
} test2;
int main(void) {
test1 t1;
test2 t2;
printf("t1 = %d\n", sizeof(t1));
printf("t2 = %d\n", sizeof(t2));
return 0;
}
Output:
t1 = 7
t2 = 8
更新
在@ryyker 和@Ajay Brahmakshatriya 的回答之后,我编写了另一个测试代码,似乎答案不适用于这种情况......如果填充大小为3,因为test1 类型的大小是3、为什么test2的大小不是9而是7?
#include <stdio.h>
typedef unsigned short u16;
typedef unsigned char u8;
typedef struct
{
u8 a;
u8 b;
u8 c;
} test1;
typedef struct
{
test1 a[2];
u8 b;
} test2;
int main(void) {
test1 t1;
test2 t2;
printf("t1 = %d\n", sizeof(t1));
printf("t2 = %d\n", sizeof(t2));
return 0;
}
Output:
t1 = 3
t2 = 7
【问题讨论】:
-
因为数组类型的对齐要求与其元素类型的对齐要求相同。
-
首先编译器找到需要更多空间的类型,并将这个空间作为基础,并据此填充其他类型。
-
typedef unsigned short u16;?为什么要创建自己的类型?如果您想要一个 16 位无符号整数变量,只需使用标准uint16_t。 -
@scmg - 到目前为止,您还没有回复任何 cmets 或答案。这些对你有帮助吗?有什么问题吗?...
-
@AndrewHenle
uint16_t在我的 pov 中不是基本类型,您需要为此包含一个标题。如果您没有自动完成功能,输入速度会更快。