Reputation:
Questions regarding, well, ultimately pointers to pointers (I suspect). Please read the questions posed in the commented code:
void doodah(char* a);
int main() {
char d[] = "message"; // one way of assigning a string.
// char* d = "message"; // another way of assigning a string, but REM'ed out for now.
cout << d << endl; // d appears not to be a pointer because cout outputs "message", and not an address. Why is this?
doodah(d); // a function call.
}
void doodah(char* a) {
cout << a << endl; // this outputs "message" - but why?! What does 'a' mean in this context?
// cout << *a << endl; // this outputs "m" - but why?! REM'ed out for now.
}
I am utterly confused! Please help.
Upvotes: 0
Views: 78
Reputation: 96845
This is what the pointer a
looks like in memory:
------------------------------------------------------------- | | 'm' | 'e' | 's' | 's' | 'a' | 'g' | 'e' | '\0' | | ^ | | | | | --- | | |a| | | --- | -------------------------------------------------------------
a
is a pointer to the first element of the string. When used in the stream inserter (operator<<()
) the compiler will match it with the overload that takes a stream on its left hand side and a pointer to a character on its right hand side. It will then attempt to print every character until it reaches the null byte ('\0'
) by evaluating characters at incremental addresses from a
.
The stream prints addresses through the overload that takes a void*
on its righthand side. You can cast your pointer to a void*
or use the standard-provided std::addressof()
function as well:
std::cout << std::addressof(a);
Upvotes: 0
Reputation: 15446
An array is a bunch of objects next to each other somewhere in memory. The variable you've set the array to is actually secretly a pointer to the first item in that array (shhh!).
The biggest difference between char *c
and char c[]
is that the latter will be a const
pointer, while the former is free to change. Also, C-Strings, like the one you have set there, are null terminated, meaning that the array ends in a binary 0 so things like cout
will know when to stop iterating (this is also known as a one pass last).
For more information, you can read up on this question.
Upvotes: 0
Reputation: 994401
cout
knows how to output strings when given a char *
. It does not attempt to print the pointer value itself.
Upvotes: 2