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

The size of structure (sizeof) in C++ doesn't correspond the real size in case of arrays

本文关键字:数组 sizeof 结构 C++      更新时间:2023-10-16

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

struct TestStructure
{
    unsigned int serial;
    int channel;
    int pedestal;
    int noise;
    int test;
};

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);

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

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 
...

请解释一下。动态数组是否在元素之间添加垫是否'sizeof'操作符显示错误的结构大小?

注:我使用GCC 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.2)。

编辑:我使用这个代码在一个宏与根CINT解释器与GCC编译库。对不起,这个bug似乎与GCC无关,而是与ROOT CINT有关。

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

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

对于数组TestStructure[n],第i(em)元素的地址必须TestStructure + i * sizeof TestStructure。如果这不是真的,那么指针算术将会严重中断。