【问题标题】:The size of structure (sizeof) in C++ doesn't correspond the real size in case of arraysC++ 中结构的大小 (sizeof) 与数组的实际大小不对应
【发布时间】:2016-08-24 08:52:52
【问题描述】:

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

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

编辑:我在带有 GCC 编译库的 ROOT CINT 解释器的宏中使用此代码。抱歉,这个错误似乎与 GCC 无关,而是与 ROOT CINT 相关。

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

【问题讨论】:

  • 如果您使用 std::vector 而不是动态数组,您的生活质量将翻倍 [需要引用]。
  • 要么我没听懂你……要么你做错了ideone.com/pBHZIQ
  • 你也不能用动态数组来做到这一点,而不是以可移植的方式。 (并且vector有一个data()成员函数)。
  • @KonstantinGertsenberger " 我不能用 std::vector 来做,这就是我使用动态数组的原因" 嗯??你认为std::vector 究竟做了什么?

标签: c++ arrays struct sizeof memory-alignment


【解决方案1】:

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

对于数组TestStructure[n],第i(th) 个元素的地址必须TestStructure + i * sizeof TestStructure。如果这不是真的,那么 指针算术 将会非常糟糕。

【讨论】:

  • 是的。对不起。似乎这个错误与 GCC 编译器无关,而是与我与 GCC 编译库一起使用的 ROOT CINT 解释器有关。我认为解释器将包装添加到结构的末尾。
  • @KonstantinGertsenberger 这是我这两天看到的第二个问题,源于 CINT 的崩溃。我对 CINT 或 ROOT 一无所知,但 CERN 说他们有 ditched CINT,也许你也应该。
猜你喜欢
  • 2017-04-26
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多