Reputation: 109
Im new to C++, so Im learning, but im having some doubts with pointers and memory addresses, I'm practicing with some exercices and got stuck with something that i haven't been able to get, I have this code
int* pointer = new int;
...
cin >> random_number;
*pointer = random_number;
now is where my concern comes in. Getting the addresses of both the dinamically allocation on the heap (pointer) doesn't have the same address than the random number. Since the pointer is pointing to the random number,
why the random number and the address the pointer points to are different addresses ??
Im self-teaching programming, i've been trying different things, its pretty clear when debugging, they're different, my question is WHY !!
Not even chat-gpt been able to tell me why 🤣
Thanks in advance and happy coding </>
Upvotes: -5
Views: 154
Reputation: 20107
The pointer is not pointing to random_number
, you are setting the int pointed to by pointer
to be equal to random_number
. When you put an asterisk in front of the pointer it dereferences it so that it behaves as the thing pointed to.
If you wanted to set pointer
to point to random_number
you would need to write pointer = &random_number;
instead. Remembering, of course, that you need to delete
the int you allocated with new
first so that it does not leak memory.
Upvotes: 3