我想知道下面代码中的数组 a 和 b 在内存中是否连续:
int main() {
int a[3];
int b[3];
return 0;
}
a[0]
,a[1]
并且a[2]
对于 应该是连续的和相同的,但是对于将分配到b
哪里有任何保证吗?b
a
如果没有,有什么方法可以强制a
和b
彼此相邻吗?即,以便它们在堆栈中彼此相邻分配。
我想知道下面代码中的数组 a 和 b 在内存中是否连续:
int main() {
int a[3];
int b[3];
return 0;
}
a[0]
,a[1]
并且a[2]
对于 应该是连续的和相同的,但是对于将分配到b
哪里有任何保证吗?b
a
如果没有,有什么方法可以强制a
和b
彼此相邻吗?即,以便它们在堆栈中彼此相邻分配。
不,C++ 不保证这些变量在内存中的位置。一个或两个甚至可能不在内存中(例如,如果它们被优化了)!
In order to obtain a relative ordering between the two, at least, you would have to encapsulate them into a struct
or class
and, even then, there would be padding/alignment to consider.
There's no guarantee that individual variables will be next to each other on the stack.
In your example you could "cheat" and simulate what you're looking for by doing this:
int main()
{
int buffer[6]
int *a = buffer;
int *b = buffer+3;
return 0;
}
Now, when you write to a[4]
you'll actually write to b[0]
.