str
is of type
char*
this means:
&str
is of type
char**
.
str[0]
is of type
char
.
&str[0]
is of type
char*
.
iostream overloads the << operator for
char*
. If you give it a
char*
, it will print as if it were a string.
If you give it any other kind of pointer (for instance a
char**
, which is different from a
char*
), it will print the address.
Note that printing
&str
is not printing a pointer to the string data. It's printing a pointer to the 'str' pointer.
That is... the below will give you different output:
1 2
|
cout << (void*)(&str); // prints a pointer to str
cout << (void*)(str); // prints a pointer to the string data
|
EDIT: also...
When I printed out the dereferenced pointer (&str)
That's not a dereferenced pointer. That's the address of a pointer.
If you want to dereference a pointer, you would use [brackets] or the * operator. In which case, you would have type
char
, which would print an individual character from the string.
Example:
1 2
|
cout << *str; // prints the 'C'
cout << str[0]; // alternative way to do the same thing. Also prints 'C'
|