pointers

So far i have constructed the following to produce the output 3 (the address) but i cant seem to make it produce the value in that address (10) :( Can anyone help me or at least explain how to go about it?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream> 
using namespace std;
int main()
{
	int *x;
	int y = 10; 
	x = &y;
	y = 3;
	cout << *x << endl;

return 0;
} 
Last edited on
3 IS the value in that address.

If you want to see the address try this:
cout << reinterpret_cast<unsigned long>(x);
(see http://www.cplusplus.com/doc/tutorial/typecasting/)
OH ok then my mistake :) So then how so that means that 10 is the address. how do we go about printing out 10 instead? oh and your link seems to be broken :(
The value of 10 no longer exists. It's replaced by 3:

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
	int *x;
	int y = 10;   // y holds 10
	x = &y;  // x points to y
	y = 3;  // y holds 3 (the value of 10 is lost)
	cout << *x << endl;  // this prints whatever is held in the var that x points to

     // since x points to y, and since y holds 3... then cout << *x prints 3

	return 0;
} 



EDIT: 10 is not the address. What the address is is irrelevent. It will be different on different machines.
Last edited on
Oh ok then i get it now! :D thank you so much! So to print out 10 we have to make y hold 10 again?
Yes.
Thank you guys so much for the explanations :D helped me understand how pointers work better
You can also assign 10 to y through x:
1
2
y = 3; //y == 3
*x = 10; //y == 10, because x points to y and by typing *x we dereferenced it 
So lets say the code looked like this instead:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream> 
using namespace std;
int main()
{
	int *x;
	int y = 10; 
	x = y;
	y = 3;
	cout << *x << endl;

return 0;
} 


How would we make x* print out 10? would we have to make y hold 10 again? Im pretty sure this wouldnt work because x would not be pointing anywhere.
No, that's not how pointers work. That code doesn't even compile for me.
Here's how it should be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream> 
using namespace std;
int main()
{
	int *x; //x is a pointer to an int
	int y = 10; //y is a normal value containing 10
	x = &y; //x now contains the address of y,and points to the value of y which is 10
	y = 3; //By changing y, we do not change x. But we do change *x, because x points to y
	cout << (*x) << endl; //this prints out 3
	(*x) = 10;
	cout << y << endl; //this prints out 10
	y = 7;
	cout << (*x) << endl; //this prints out 7

	//this prints out the memory addres where y is stored. It could be anything
	cout << reinterpret_cast<unsigned long>(x) << endl;

	x = 10; //Don't do this. The program will very likely crash if you try to access *x after this.

return 0;
}
Last edited on
OK i see how it works :D just wanted to make sure i got pointers completely. Thank you L B!
Topic archived. No new replies allowed.