Why would the dereferenced first element of a call argument pointer give me the string?

Here's the code:



#include <iostream>

using namespace std;

void printName(char *str);

int main()
{

printName("Chicken");

return 0;
}

void printName(char *str)
{
cout << &str << " " << &str[0] << endl;
}



I am thoroughly confused by this. When I printed out the dereferenced pointer (&str) I got the address of the pointer. When I printed out the dereferenced first element of the pointer (&str[0]) I got the string argument that I called in ("Chicken"). What is going on here?? Why did this happen?
Last edited on
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' 
Last edited on
Oh okay, I think I get it. So the cout command printing out char*'s as strings has less to do with logic than it does about C++ syntax. Is that right?

Note that printing &str is not printing a pointer to the string data. It's printing a pointer to the 'str' pointer.


Is this another way of saying that it's printing the address of the pointer?

Thanks Disch! This was very helpful!!!
Oh okay, I think I get it. So the cout command printing out char*'s as strings has less to do with logic than it does about C++ syntax. Is that right?


No, it doesn't have anything to do with syntax. It's a carry over from C, when they used char* as a psuedo-string type.
No, it doesn't have anything to do with syntax. It's a carry over from C, when they used char* as a psuedo-string type.


The reason I think it's more related to syntax than logic is because there doesn't seem to be any logical reason why a memory location that contains the address of another memory location would represent the entire array of character variables associated with it. It's convenient but it's something that must be committed to memory rather than deduced like.. say... the logic of an if function.
Topic archived. No new replies allowed.