【发布时间】:2013-11-20 16:27:26
【问题描述】:
我的理解是,如果要对齐,则必须明确指定数组的对齐方式。
但是,我声明的浮点数组似乎总是与 16 字节对齐。
float *ptr1 = new float[1];
cout<<"ptr1: "<<ptr1<<endl;
float *ptr2 = new float[3];
cout<<"ptr2: "<<ptr2<<endl;
float arr1[7];
cout<<"arr1: "<<arr1<<endl;
float arr2[9] __attribute__((aligned(2)));
cout<<"arr2: "<<arr2<<endl;
这是输出
ptr1: 0x13dc010
ptr2: 0x13dc030
arr1: 0x7fff874885c0
arr2: 0x7fff87488590
这是有原因的吗?我正在使用 gcc 4.6.3
但是,如果它是指向浮动位置或静态分配的指针,我看不到它
static float arr3[9] __attribute__((aligned(2)));
cout<<"arr3: "<<arr3<<endl;
float *x;
cout<<"x: "<<x<<endl;
输出:
arr3: 0x4030b2
x: 0x7fff8c7dd9e8
此代码在 x64 上运行。
【问题讨论】:
-
这取决于你的编译器。查看他们的文档。附言您的
float *x从未初始化,因此结果基本上是随机的。 -
我的 gcc 4.8.1 默认只对齐 8 个字节。那是因为
malloc实现会这样做(...operator new调用)。一言以蔽之:不要指望它。
标签: c++ c memory-management