Pointer Question

Started by
5 comments, last by scjohnno 15 years, 10 months ago
This question is probably a silly one but here is the code: #include "stdafx.h" #include <iostream> typedef unsigned short int USHORT; int main() { using namespace std; USHORT myAge; USHORT *pAge = &myAge cout <<"Address of myAge: " << &myAge << endl; cout <<"Address of *page: " << &pAge << endl; return 0; } This returns: Address of myAge: 0012FF60 Address of *pAge: 0012FF54 Why are the addresses not the same?
Advertisement
Because they're not the same. One is a pointer to myAge, the other is a pointer to pAge. (and your label is incorrect on the second line of output)
I'm not trying to be difficult or anything, but I thought that I created a variable myAge and assigned the address of myAge to the pointer pAge. I didn't do that here?
Quote:Original post by Anexa85
I'm not trying to be difficult or anything, but I thought that I created a variable myAge and assigned the address of myAge to the pointer pAge. I didn't do that here?


You did, and then you printed the address of pAge rather than its value. Pointers have addresses too.
Oh ok! I see now, so I just need to print the pointer and not the address of it. Thank you!
Quote:Original post by Anexa85
I'm not trying to be difficult or anything, but I thought that I created a variable myAge and assigned the address of myAge to the pointer pAge. I didn't do that here?


The problem is in the way you're printing out the values.

You should have written:

cout <<"Address of myAge: " << &myAge << endl;cout <<"Address of page: " << pAge << endl;  // No address-of operator here!


You want to print out the memory location that is stored inside the pointer. Not the memory location of the pointer itself.
Quote:Original post by fpsgamer
You should have written:

cout <<"Address of page: " << pAge << endl;  // No address-of operator here!


You want to print out the memory location that is stored inside the pointer. Not the memory location of the pointer itself.


That's actually displaying the value of pAge, which is the address of myAge. I think you just made a typo. :)

This topic is closed to new replies.

Advertisement