A question about pointers?

Jun 20, 2013 at 9:56am
What is the difference between these two codes?
1
2
3
4
5
	int *ptr = new int;
	int x(7);
	cout<<"x:"<<x<<endl;//output 7;
	*ptr = x;
	cout<<"&ptr: "<<&ptr<<endl;


and the second one:

1
2
3
4
5
6
	int *ptr = new int;
	int x(7);
	cout<<"x:"<<x<<endl;//output 7;
	*ptr = x;

	cout<<"ptr: "<<ptr<<endl;


which one prints me the adress of ptr? and what the other one prints?

thank you!
Jun 20, 2013 at 10:01am
the first one prints the address of the pointer.
the second prints the value of the pointer (somehow the pointer itself)
Jun 20, 2013 at 10:05am
That it would be clear consider the following simple example

1
2
3
4
5
6
7
8
9
int x = 10;
int *p = new int( 20 );

std:;cout << x << std::endl; // prints what is stored in x that is 10
std:;cout << &x << std::endl; // prints the address of x

std:;cout << p << std::endl; // prints what is stored in p 
                             // that is the address of the allocated memory
std::cout << &p << std::endl; // prints the address of p itself 
Last edited on Jun 20, 2013 at 10:06am
Jun 20, 2013 at 10:09am
thanks
Topic archived. No new replies allowed.