User800222 User800222 - 4 months ago 22
C++ Question

C++ pointer assigning char array's address

In many examples I see, if

int x = 0; int *ptr; ptr = &x
then ptr is saving x's address info. I'm kinda confused why if the following code does perform the same. When I print the
, it shows:


rather than the address of the p[0].

#include <iostream>
#define show(a) std::cout<<a<<std::endl;
#define Syswait std::system("pause");

int main() {

char p[] = "app";
char *ptr;
ptr = &p[0];


Can anyone explain? Thanks.

rex rex
Answer Source

Because that is what the function is declared to do. ptr is a char* (char pointer) and there is an overload specifically defined to accept it.


actually calls the function declared as:

template< class Traits >
basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os,  
                                        const char* s );

From the link we learn what the function will do:

After constructing and checking the sentry object, inserts successive characters from the character array whose first element is pointed to by s.

To avoid this, cast to void *:

std::cout << (void *)a;