首先看看下面这个程序输出
#include <stdio.h>
#include <stdint.h>
#include <stdalign.h>
typedef uint32_t MYSIZE;
struct Node
{
char *Data;// 1 --- 指针变量,如果在64位操作系统上,占用8byte
struct Node *Next;// 2 --- 同样是指针变量,如果在64位操作系统上,占用8byte
MYSIZE Size;// 3 --- uint32_t 32位uint占用4byte
MYSIZE Pos;// 4 --- uint32_t 32位uint占用4byte
};
int main() {
printf("alignof struct Node: %d\n", alignof(struct Node));
printf("struct sizeof Node: %d\n", sizeof(struct Node));
return 0;
}
output:
alignof struct Node: 8
struct sizeof Node: 24
计算一个struct大小对依据就是 alignof 的大小。一句话就是结构体的内存布局根据 alignof 的长度进行对齐布局的。为了便于说明,将上面程序中结构体Node中的4个变量编号:
- Data
- Next
- Size
- Pos
结下来使用编号来表示内存布局:
1 1 1 1 1 1 1 1 // 长度8
2 2 2 2 2 2 2 2 // 长度8
3 3 3 3 4 4 4 4 // 长度4 加 长度4
这里是以长度8对齐的,即alignof 为8,struct node 的总长度为24,合理解释来程序输出。
下面调整一下结构体,将3提到2前面,看看程序布局会发生什么变化。
struct Node
{
char *Data;// 1 --- 指针变量,如果在64位操作系统上,占用8byte
MYSIZE Size;// 3 --- uint32_t 32位uint占用4byte
struct Node *Next;// 2 --- 同样是指针变量,如果在64位操作系统上,占用8byte
MYSIZE Pos;// 4 --- uint32_t 32位uint占用4byte
};
程序输出output:
alignof struct Node: 8
struct sizeof Node: 32
为什么结构体的大小会变大为32呢?
看看下面的结构布局:
1 1 1 1 1 1 1 1
3 3 3 3
2 2 2 2 2 2 2 2
4 4 4 4
按照alignof=8进行对齐布局,只能是这么一个情况。所以,结构体大小就变成来32。