std::cout treats pointers to char in a special way, so that, for instance,
std::cout << "a string literal" ;
will print out
a string literal instead of the address that's fed to cout.
If you want to display the address that a pointer to char holds, then cast it to another type:
1 2 3 4 5 6 7
|
#include <iostream>
int main()
{
char* ch ;
std::cout << static_cast<void*>(ch) << '\n' ;
}
|
1 2
|
char* ch; //create a pointer to one byte of memory?
cout << ch;
|
causes undefined behavior. ch is treated as a pointer to a c style string and dereferenced. Not good.
Next, this compiles and runs:
1 2 3 4
|
char* ch;
ch = "5";
cout << ch;
return 0;
|
Output: 5
But why aren't I getting an address? Shouldn't I have to say: cout << *ch to get the value being pointed at by ch? |
*ch is a single char. "5" is an array of characters consisting of '5' and '\0'. If you were to
cout << *ch
the output would also be 5.
And to assign a value to ch, shouldn't I have to do this: *ch = "5" (in order to dereference ch as a pointer and say I'm assigning 5 to the value ch is pointing at).
|
*ch is a single char. "5" is an array of char. You can't assign one to the other. On the other hand you can make a pointer to char point at an array of char.
Even more curiously:
1 2 3
|
int* x;
cout << x;
return 0;
|
Behaves as expected.
Output: a valid address.
So whats different with char pointer? |
cout interprets a pointer to char as a C-style string. Obviously, there's no reason to treat a pointer to int in the same way.
AND THEN (I know right?) This compiles but crashes:
1 2 3
|
int* x;
*x = 5;
return 0;
|
Why can't I assign a value to the memory allocated for x?
|
You can. By saying
x = some_pointer_value
. x is a pointer that hasn't been pointed at any memory and has some random value, so when you dereference it (
*x) you're interpreting that random value as an address and assigning the memory that it points to a value. In other words, you're trashing memory you don't own -- undefined behavior.