3

My understanding about assigning an array to a pointer is that the pointer is pointing at the first index of the array, so when printout the pointer, it should print out the address of the first index of the array, but how come in this case the cout printed out the value of the whole array? even though I explicitly indicated that I wanted the address of the first index

char foo[] = {'A','B','C','\0'};
char* p = foo;
char* q = &(foo[0]);
cout <<"from p:  " << p << endl;
cout << "from q: " <<  q << " " << &(foo[0]) <<  endl;

//output
from p:  ABC
from q: ABC ABC

the second question is that I see the difference between those two lines is that one is an array of pointer to char, the other is a pointer to a char array, is that correct? is the parenthesis necessary?

 char* bar1[4];
 char (*bar2)[4] = &foo;
 cout << "address of foo is  " << bar2  << endl;
 //output
 address of foo is  0x7fff192f88b0

The address of the foo array should be the same as the address of A, right? How do I printout the address of A? since I failed to do so. Thank you very much

1 Answer 1

6

<< has a dedicated overload for const char *, because that's what a C-style string is. Try this:

cout << static_cast<const void *>(bar2) << endl;
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, what if I changed the foo to foo={'A','B','C'} without the null-terminator, it should be treated as a char array instead of C-string right?
@ClintHui: No, because the content doesn't affect the type.
so there is no actual char array in C++, all will be treated as C-String? Thanks
@ClintHui: foo really is a char array (it's of type char [4]); but in almost all situations it decays to &foo[0], i.e. char *.
Thanks, is there a way to explicitly print out the address of A? Thanks, since the << is overloaded.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.