最近,我正在学习有关内存对齐和相关问题的知识,这使我找到了以下程序:
#include <cstdio>
#include <cstdint>
struct XX
{
uint8_t a;
uint32_t b;
uint16_t d;
uint64_t c;
};
int main()
{
printf("\n\ntype size: %zu\n", sizeof(XX));
XX one;
XX two;
XX three;
printf("addresses of one-three:\n\t%p\n\t%p\n\t%p\n", reinterpret_cast<void *>(&one), reinterpret_cast<void *>(&two), reinterpret_cast<void *>(&three));
printf("\ndifference of addresses between one and two: %lu\n", reinterpret_cast<unsigned long>(&one) - reinterpret_cast<unsigned long>(&two));
printf("difference of addresses between two and three: %lu\n", reinterpret_cast<unsigned long>(&two) - reinterpret_cast<unsigned long>(&three));
printf("alignment of type alone: %zu\n", alignof(XX));
XX arr[2];
printf("\ndifference of addresses in array: %lu\n", reinterpret_cast<unsigned long>(&arr[1]) - reinterpret_cast<unsigned long>(&arr[0]));
printf("alignment of array type: %zu\n", alignof(XX[]));
}
我使用GCC 8.1.0将其编译为:
g ++ -std = c ++ 17 -O0 main.cpp
输出说:
为什么独立变量之间的字节数超过8个?