There is the following code:
int main() { int a = 1; int b = 2; printf("%d", &a - &b); return 0; }
Question 1: Why is the address of the variable a greater than the address b.
Question 2: Why is the address difference 3?
There is the following code:
int main() { int a = 1; int b = 2; printf("%d", &a - &b); return 0; }
Question 1: Why is the address of the variable a greater than the address b.
Question 2: Why is the address difference 3?
I hasten to please that the &a - &b
construction in my opinion can work as you please. Logically, memory for variables a and b is allocated on the stack. Those. from older addresses to younger ones. And the memory should be allocated in the order of variable declarations. This is the answer to question 1.
Usually, variables on the stack are allocated in a row, without gaps. But here, how lucky, because Memory alignment can be enabled. And then all addresses of all objects will be multiple to some values ​​(for example, 8 bytes). Moreover, for me personally, the program displays the answer 1. This means that the difference in the addresses is equal to one element of the size of int. And what will happen if the compiler tries to optimize these instructions - generally a mystery. And try to find the difference with the program like this:
#include <stdio.h> int main() { int a = 1; int b = 2; printf("%d", (char*)&a - (char*)&b); return 0; }
Please note that the inclusion of the stdio.h
header is necessary, otherwise the compiler may tear down the roof a little.
I have a difference in debug mode 8. In release 2 mode.
Debug overloads new delete and perhaps some low-level constructors for int or something like that.
That is, int a is first created; Then a temporary variable storing 1. then b then a variable for 2.
int
? - gecube pmIn x86 architecture, the stack grows from top to bottom. By the way, in the Spark architecture the stack grows the other way round: from smaller addresses to large ones, and the opposite picture will be observed there.
Source: https://ru.stackoverflow.com/questions/148089/
All Articles