TRod
TRod

Reputation: 293

Pointer outputs

I'm just trying to understand the difference in how you output pointers.

let's say I have:

int x = 100;
int*p = &x; 

what would each of the following do?

cout << p << endl;
cout << *p << endl;
cout << &p << endl;

Upvotes: 0

Views: 1295

Answers (2)

slugonamission
slugonamission

Reputation: 9632

int*p = &x; creates a pointer, p, which points to the variable x. A pointer is actually implemented as a variable which holds the memory address which it is pointing to. In this case, you will get the following. For the purposes of this example, assume that x is stored at 0x1000 and p is stored at 0x1004:

  • cout << p << endl; will print the address of x (0x1000).
  • cout << *p << endl; will dereference the pointer, and hence will print the value of x (100).
  • cout << &p << endl; takes the address of p. Remember that pointers are simply variables in their own right. For this reason, it will print 0x1004.

Upvotes: 3

4pie0
4pie0

Reputation: 29724

cout << p << endl;  // prints the adress p points to,
                    // that is the address of x in memory
cout << *p << endl; // prints the value of object pointed to by p,
                    // that is the value of x
cout << &p << endl; // prints the address of the pointer itself

Upvotes: 3

Related Questions