Reputation: 47
int *n=(int *)5;//Valid
cout<<*n;//Invalid
Why pointer n can point to an address although 5 is not a memory location. Why I can not print out the screen the value of n.
Upvotes: 1
Views: 149
Reputation: 114230
Short answer: because the value of n
is n
. *n
is the value at n
: i.e., what it's pointing to.
If you want n
to point to the value 5 rather than the address 5, you have to make it do so:
int x = 5;
int* n = &x;
Now n
is the address of a stack location that has 5 as its value.
Upvotes: 1
Reputation: 251
You are attempting to dereference memory address 0x5, which is probably restricted memory.
int *n=(int *)5;
You are casting the integer literal 5 as an int*
. What that means is you are saying 0x5 is an address. When attempting to dereference that pointer with *n
, you will get an error.
Instead, you would need to do something like:
int five = 5;
int *n = &five;
cout << *n;
Don't use (int *)
, use the address-of operator &
. Also keep in mind you cannot take the address of a literal other than string literals.
Upvotes: 3