I've written the following code trying to solve a challenge which requests an array-like structure without using them:
#include <iostream>
int main(){
int x = 132,y = 33,z = 87;
int *i = &x;
std::cout << x << " " << y << " " << z << "\n";
std::cout << &x << " " << &y << " " << &z << "\n";
std::cout << i << " " << i-1 << " " << i-2 << "\n";
std::cout << *i << " " << *(i-1) << " " << *(i-2) << "\n";
}
I found that the difference between 2 variables' addresses (&y-&x) to be -1 and I've adapted the code subsequently I don't understand why the last defined variable is allocated "before" (meaning, a previous address).
I would have think &y-&x = 1, honestly.
Can you give me a few pointers? (no pun intended :P) Oh, I know that code is bad practice - but does it have drawbacks or exceptions?
Thank you in advance
This practice is as bad as it can get.
The stack layout is not specified; even if the variable actually has a on-stack representation (which it may not have, if you don't take the variable address and the optimizer moves it to registers), the order between variables and the padding (i.e. the difference between pointers) is not specified.
You can get a pointer to the local variable, but you can't do pointer arithmetics on it - you get undefined behavior (unless, of course, we're talking about local array variable).
Finally, there is at least one platform where abs(&y - &x) is never 1 (because stack vars are 16b-aligned).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With