我的理解是,如果您希望对齐数组,必须明确指定其对齐方式。
然而,我声明的浮点数组似乎总是对齐到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。
但是,如果它是指向float位置或静态分配的指针,我就看不到它了。
static float arr3[9] __attribute__((aligned(2)));
cout<<"arr3: "<<arr3<<endl;
float *x;
cout<<"x: "<<x<<endl;
输出:
arr3: 0x4030b2
x: 0x7fff8c7dd9e8
这段代码是在x64架构上运行的。
float *x
从未被初始化,因此其结果基本上是随机的。 - Mark Ransommalloc
实现了这一点(...这也是operator new
调用的原因)。总之,不要指望它。 - Damon