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>
usingnamespace std;
int main()
{
int *x;
int y = 10;
x = &y;
y = 3;
cout << *x << endl;
return 0;
}
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.
#include <iostream>
usingnamespace 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<unsignedlong>(x) << endl;
x = 10; //Don't do this. The program will very likely crash if you try to access *x after this.
return 0;
}