Reputation: 95
I'm wondering if the arrays a[]
and b[]
in the code below are contiguous in memory:
int main() {
int a[3];
int b[3];
return 0;
}
a[0]
,a[1]
and a[2]
should be contiguous and the same for b
, but are there any guarantees on where b
will be allocated in relation to a
?
If not, is there any way to force a
and b
to be contiguous with eachother? i.e. - so that they are allocated next to eachother in the stack.
Upvotes: 7
Views: 1293
Reputation: 62472
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]
.
Upvotes: 4
Reputation: 385144
No, C++ makes no guarantee about the location of these variables in memory. One or both may not even be in memory (for example if they are optimised out)!
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.
Upvotes: 18