【发布时间】: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