我知道对于一个结构体
struct sequences{
int a[3];
int b[3];
} sequence = {{1,2,3},{4,5,6}};
a 和 b 彼此相邻存储,即如果我这样做
int i;
for(i=0; i<6; ++i){
printf("%d", sequence.a[i]);
}
我将得到输出 123456。
我尝试将这两个数组存储在主函数之外,但没有存储在结构中
int a[3] = {1,2,3};
int b[3] = {4,5,6};
当我尝试同样的事情时,
for(i=0; i<6; ++i){
sum = sum + a[i];
}
我得到输出 123045。因此,如果不在结构中,显然不能保证它们彼此相邻存储。
如果我改为在其后存储一个数组和一个整数,它们似乎总是在内存中相继出现,即
int a[3] = {1,2,3};
int x = 1000;
和
for(i=0; i<4; ++i){
printf("%d", a[i]);
}
给出 1231000。
我意识到编译器可能会根据我无法控制的一些复杂因素来选择存储变量的位置,但是是否有任何规则可以保证两个变量相对于彼此的存储位置,就像结构一样?
最佳答案
C 标准仅保证结构的非位域成员按顺序存储在内存中,元素之间有可选的填充,并且数组的成员按顺序存储且没有填充。
关于结构,C standard 的第 6.7.2.1p15 节状态:
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
没有关于一个不相关变量在内存中与另一个变量的放置的保证。
此外,当您这样做时:
struct sequences{
int a[3];
int b[3];
} sequence = {{1,2,3},{4,5,6}};
...
int i;
for(i=0; i<6; ++i){
printf("%d", sequence.a[i]);
}
您调用 undefined behavior因为您的索引超出了数组成员 a
的末尾。在这种情况下,实现不需要读取 b
的元素。在仍然符合标准的情况下,最好的办法是比较 &sequence.a[3] == &sequence.b[0]
关于c - "close"到其他变量在C中存储的规则是什么,如果有的话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688952/