0
How exactly does this work? why does it output 5?
#include <iostream> using namespace std; int main() { int *p; int x=5; p=&x; cout<<*p; }
2 ответов
+ 3
It outputs 5 because you are dereferencing x, which contains the value of 5.
How it works exactly when compiled:
mov DWORD PTR [rbp-12], 5
//we move the value of 5 onto the stack, aka "x = 5"
lea rax, [rbp-12]
//we load the address on the stack where we just stored x, and then store it in the RAX register for operations.
mov QWORD PTR [rbp-8], rax
//now we move the address of "x" onto the stack where variable p will be stored.
And so now, this means p points to the location on the stack where "x" is, and when you deference it, you get the value of x.
+ 1
here, p is a pointer pointed to null currently.
after that you assigned 5 to x; somewhere in memory x is being saved. so it has a address.
let the address of x is "0X".
and now p is pointing to address of x which is "0X".
since you are printing *p, your program prints the value saved at location "0X" , that's why you got 5.