数据对齐是咋回事呢
数据对齐是怎么回事呢?
数据对齐是怎么回事呢?
------解决方案--------------------
数据对齐是为了加快数据访问的一种技术,比如在32位字长的机器上,通常使用4字节对齐,如果一个32为整数的地址是4的倍数,只需要一次访问内存就可以取出,否则需要访问两次内存。
下面的可以举个例子
struct Node
{
char c;
int n;
} item;
#include <stdio.h>
int main(void)
{
struct Node item;
printf( "sizeof(struct Node) = %d\n ", sizeof(struct Node));
printf( "address of item.c = %#.08x\n ", &item.c);
printf( "address of item.n = %#.08x\n ", &item.n);
return 0;
}
程序性输出结果:
sizeof(struct Node) = 8
address of item.c = 0x0012ff78
address of item.n = 0x0012ff7c
可见,虽然 c 只占用了一字节,但是为了对齐4字节边界,下一个元素n的地址比c的地址大了4,
中间空出了三个字节!
数据对齐是怎么回事呢?
------解决方案--------------------
数据对齐是为了加快数据访问的一种技术,比如在32位字长的机器上,通常使用4字节对齐,如果一个32为整数的地址是4的倍数,只需要一次访问内存就可以取出,否则需要访问两次内存。
下面的可以举个例子
struct Node
{
char c;
int n;
} item;
#include <stdio.h>
int main(void)
{
struct Node item;
printf( "sizeof(struct Node) = %d\n ", sizeof(struct Node));
printf( "address of item.c = %#.08x\n ", &item.c);
printf( "address of item.n = %#.08x\n ", &item.n);
return 0;
}
程序性输出结果:
sizeof(struct Node) = 8
address of item.c = 0x0012ff78
address of item.n = 0x0012ff7c
可见,虽然 c 只占用了一字节,但是为了对齐4字节边界,下一个元素n的地址比c的地址大了4,
中间空出了三个字节!