Suppose I have a C struct defined as follows:
假设我有一个C结构定义如下:
typedef struct
{
double array1[2];
} struct0_T;
How is the memory laid out? Is struct going to hold just a pointer or the value of the two doubles? Before I thought the struct holds a pointer, but today I found out (to my surprise) that the values are stored there. Does it vary between different compilers?
记忆是如何布局的? struct只能保持一个指针或两个双打的值吗?在我认为struct有一个指针之前,但今天我发现(令我惊讶的是)值存储在那里。它在不同的编译器之间有所不同吗?
2 个解决方案
#1
9
The struct contains the two values. The memory layout is .array1[0]
, followed by .array1[1]
, optionally followed by some amount of padding.
该结构包含两个值。内存布局为.array1 [0],后跟.array1 [1],可选地后跟一些填充量。
The padding is the only part that of this that can vary between compilers (although in practice, with the only member of the struct being an array there will almost certainly be no padding).
填充是唯一可以在编译器之间变化的部分(尽管在实践中,结构的唯一成员是数组,几乎肯定没有填充)。
Although you may have heard that an array in C is a pointer, that is not true - an array is an aggregate type consisting of all the member objects, just like a struct. It is just that in almost all expression contexts, an array evaluates to a pointer to its first member.
虽然你可能听说C中的数组是一个指针,但事实并非如此 - 数组是一个由所有成员对象组成的聚合类型,就像结构一样。几乎在所有表达式上下文中,数组都会计算出指向其第一个成员的指针。
#2
2
The above structure declaration just inform the compiler that variables of that struct
data structure type will take sizeof(struct0_T)
bytes of memory and this memory will be allocated once a variable of that type will be instantiated.
上面的结构声明只是通知编译器该struct数据结构类型的变量将采用sizeof(struct0_T)字节的内存,并且一旦该类型的变量将被实例化,将分配该内存。
struct0_T s;
Now, s
contains an array of two doubles
. There will be no padding in this case.
现在,s包含两个双精度数组。在这种情况下将没有填充。
#1
9
The struct contains the two values. The memory layout is .array1[0]
, followed by .array1[1]
, optionally followed by some amount of padding.
该结构包含两个值。内存布局为.array1 [0],后跟.array1 [1],可选地后跟一些填充量。
The padding is the only part that of this that can vary between compilers (although in practice, with the only member of the struct being an array there will almost certainly be no padding).
填充是唯一可以在编译器之间变化的部分(尽管在实践中,结构的唯一成员是数组,几乎肯定没有填充)。
Although you may have heard that an array in C is a pointer, that is not true - an array is an aggregate type consisting of all the member objects, just like a struct. It is just that in almost all expression contexts, an array evaluates to a pointer to its first member.
虽然你可能听说C中的数组是一个指针,但事实并非如此 - 数组是一个由所有成员对象组成的聚合类型,就像结构一样。几乎在所有表达式上下文中,数组都会计算出指向其第一个成员的指针。
#2
2
The above structure declaration just inform the compiler that variables of that struct
data structure type will take sizeof(struct0_T)
bytes of memory and this memory will be allocated once a variable of that type will be instantiated.
上面的结构声明只是通知编译器该struct数据结构类型的变量将采用sizeof(struct0_T)字节的内存,并且一旦该类型的变量将被实例化,将分配该内存。
struct0_T s;
Now, s
contains an array of two doubles
. There will be no padding in this case.
现在,s包含两个双精度数组。在这种情况下将没有填充。