C++中的结构大小(sizeof)与数组的实际大小不一致

Kon*_*ger 1 c++ arrays struct sizeof memory-alignment

我使用以下结构的动态数组:

struct TestStructure
{
    unsigned int serial;
    int channel;
    int pedestal;
    int noise;
    int test;
};
Run Code Online (Sandbox Code Playgroud)

所述的sizeof(TestStructure)返回20,所以我假定有在结构上没有填充/比对.这在逻辑上是因为只有4字节类型.

但我发现结构的大小乘以元素数不等于数组的大小.阵列的元素之间还有一个额外的填充!因此,在以下代码中:

TestStructure* test_struct = new TestStructure[element_count];
for (int i = 0; i < element_count; i++)
  FillStructure(test_struct, i, i, i, i, i, i); // assigning 'i' for all elements

Long_t size_value = element_count * sizeof(TestStructure);
unsigned char* p_value = new unsigned char[size_value];
memcpy(p_value, test_struct, size_value);
Run Code Online (Sandbox Code Playgroud)

字符的输出数组包含元素之间的附加填充:

sizeof(TestStructure) = 20. element_count = 10. size_value = 200. char array in the hex format:
0 0 0 0 
0 0 0 0 
0 0 0 0 
0 0 0 0
0 0 0 0
6c 6c 2f 6c

1 0 0 0 
1 0 0 0 
1 0 0 0 
1 0 0 0 
1 0 0 0 
6f 70 74 2f 

2 0 0 0 
...
Run Code Online (Sandbox Code Playgroud)

请解释一下.动态数组是否在元素之间添加了pad或者'sizeof'运算符是否显示了错误的结构大小?

PS我使用GCC 5.4.0(Ubuntu 5.4.0-6ubuntu1~16.04.2).

编辑:我在宏中使用此代码与ROOT CINT解释器与GCC编译库.Sorrry,似乎这个bug与GCC有关,但与ROOT CINT无关.

EDIT2:是的,在我的ROOT宏中(由CINT解释器执行)sizeof(TestStructure)返回24,之后当我调用GCC编译库的函数(包含上面列出的代码片段)时,sizeof(TestStructure)返回20 in编译的功能.

Bat*_*eba 7

虽然编译器可以在a的末尾添加打包,但struct编译器在制造数组时绝对不能在元素之间添加额外的打包.

对于数组TestStructure[n],第i个元素的地址必须是TestStructure + i * sizeof TestStructure.如果这不是真的那么指针算法就会破坏.