C++ 中结构的大小 (sizeof) 与数组的实际大小不对应
The size of structure (sizeof) in C++ doesn't correspond the real size in case of arrays
我使用以下结构的动态数组:
struct TestStructure
{
unsigned int serial;
int channel;
int pedestal;
int noise;
int test;
};
sizeof(TestStructure) returns 20,所以我假设结构中没有padding/alignment。这是合乎逻辑的,因为只有 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' 运算符是否显示错误的结构大小?
P.S。我使用 GCC 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.2).
编辑:我在带有 GCC 编译库的 ROOT CINT 解释器的宏中使用此代码。抱歉,这个错误似乎与 GCC 无关,而是与 ROOT CINT 有关。
EDIT2:是的,在我的 ROOT 宏中(由 CINT 解释器执行)sizeof(TestStructure) returns 24 和之后,当我调用 GCC 编译库的函数(包含上面列出的代码片段)时,sizeof(TestStructure) returns 20 在编译函数中。
虽然编译器可以在 struct
的末尾添加包装,但编译器绝对 不能 在制造数组时在元素之间添加额外的包装。
对于数组 TestStructure[n]
,第 i(th) 个元素的地址 必须 为 TestStructure + i * sizeof TestStructure
。如果这不是真的,那么 指针算术 会严重崩溃。
我使用以下结构的动态数组:
struct TestStructure
{
unsigned int serial;
int channel;
int pedestal;
int noise;
int test;
};
sizeof(TestStructure) returns 20,所以我假设结构中没有padding/alignment。这是合乎逻辑的,因为只有 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' 运算符是否显示错误的结构大小?
P.S。我使用 GCC 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.2).
编辑:我在带有 GCC 编译库的 ROOT CINT 解释器的宏中使用此代码。抱歉,这个错误似乎与 GCC 无关,而是与 ROOT CINT 有关。
EDIT2:是的,在我的 ROOT 宏中(由 CINT 解释器执行)sizeof(TestStructure) returns 24 和之后,当我调用 GCC 编译库的函数(包含上面列出的代码片段)时,sizeof(TestStructure) returns 20 在编译函数中。
虽然编译器可以在 struct
的末尾添加包装,但编译器绝对 不能 在制造数组时在元素之间添加额外的包装。
对于数组 TestStructure[n]
,第 i(th) 个元素的地址 必须 为 TestStructure + i * sizeof TestStructure
。如果这不是真的,那么 指针算术 会严重崩溃。