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)返回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
。如果这不是真的,那么指针算术将会严重中断。
相关文章:
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 如何将数组传递给使用 sizeof 的函数?
- Sizeof返回的是指针大小,而不是数组大小.有其他方法可以找到尺寸吗
- 使用 sizeof 计算数组中的元素数时的结果不同
- sizeof(空结构)和sizeof(带有空数组的结构)之间的区别?
- 有人可以告诉我为什么我在这里使用sizeof()函数无法找到数组的长度
- 字符串数组上的C sizeof将传递给函数时未返回预期结果
- 使用sizeof()计算数组大小
- 数组中的值之和返回内存地址,除非sizeof(array)/2
- sizeof引用GDB中的数组
- 你能使用 sizeof() 打印由 char * 指向的数组的大小吗?
- sizeof()运算符为数组和指向数组的指针返回不同的值
- 为什么对于某些数组A,sizeof(A)在函数内部不起作用
- 数组和sizeof编译错误C++时出现问题
- sizeof 在传递模板数组时如何工作
- 为什么 sizeof 运算符在传递给方法的数组上使用时返回错误的值
- 对作为参数传递的数组使用sizeof
- 作为参数传递的数组sizeof的奇怪行为
- 方法中使用的静态模板成员数组sizeof