int main()
{
int a = 10;
int *p; // int *p = a; gives me an error: invalid conversion from int to int *.
// Tell me why?
*p = a; // while this runs
cout << &a <<" "<<p;
}
Secondly &a and p gives 2 different values. According to me Address of a and the value stored in pointer p should be the same?
int *p = a, interpreted literally, takes the value stored inaand tries to interpret it as a memory address to store inp. While computationally legal, C++ won’t allow this without an explicit typecast, because this is normally not what you want to do.The reason why the statement
int *p = ais different from*p = ais simple: the first statement, shorthand for the followingis initializing the pointer, so it expects a memory address on the RHS, while the second statement is assigning a value to the location pointed to by
p, so expects (in this case) an integer on the RHS.If you want to initialize
pto point toa, you can useint * p = &aorp = &ainstead, where&is the address-of operator. NEVER try to dereference uninitialized pointers! You will end up touching memory in an essentially arbitrary location, which could cause a segmentation fault (resulting in crash) or start overwriting other data in your program (resulting in obscure and non-reproducible bugs).When you run your example code,
pand&ahave different values precisely becausepwas never assigned to point to the address ofa. Some short background on why you might get any nonzero value inpat all: local variables are assigned from a special region of memory known as the stack, which also stores information about function calls and return addresses. Each process has their own stack. Crucially, though, unused regions of the stack aren’t really zeroed out or otherwise cleaned up before use (except maybe in debug builds, which tend to assign really obvious values like0xCCCCCCCCor0xBAADF00Dto uninitialized pointers). If your compiler doesn’t automatically set default values for you (and release builds generally won’t have such automatic initialization, for efficiency’s sake), what you are seeing inpis what happened to be located in the memory assigned topbefore your program set up its stack frame.