Why does the following code compile:
int main()
{
int j = 1;
int *jp = &j;
cout << "j is " << j << endl;
cout << "jp is " << jp << endl;
cout << "*jp is " << *jp << endl;
cout << "&j is " << &j << endl;
cout << "&jp is " << &jp << endl;
}
but not this?
#include <iostream>
using namespace std;
int main()
{
int j = 1;
int *jp;
*jp =& j; // This is the only change I have made.
cout << "j is " << j << endl;
cout << "jp is " << jp << endl;
cout << "*jp is " << *jp << endl;
cout << "&j is " << &j << endl;
cout << "&jp is " << &jp << endl;
}
This compiles when I do jp = &j, why? I have only initialized jp in another line, this is not making sense to me.
jpis a pointer. Its value (jp) is a memory address. It points to (*jp)an integer. When you doThis sets the value to the memory address of
j. So now*jpwill point toj. When you doThis sets the value of the thing
jpis pointing to to the memory address ofj. When you do:jpis not pointing to anything yet – its value is uninitialized.*jp = &jtries to follow the memory address of the value ofjp, which is something random, and set it to&j… which will probably cause a segfault.To clarify: The
*in (int *jp;) is a different one than in*jp = .... The former just declaresjpas a pointer. The latter defines how you do the assignment. To make it even more explicit, doing:is the same as
Note there is no
*on the assignment.