I met a strange problem. In C++
char s[]="123abc89"; cout<<s[0]<<endl; //1 it is right cout<<&s[0]<<endl; // I can't understand why it is "123abc89" Thanks a lot in advance.
s[0] is the 1st element of character array. &s[0] is the address of the 1st element, the same to the address of the array. Given the start address of a character array, std::cout prints out the whole string starting at that address, using the following overload of operator<< :
// prints the c-style string whose starting address is "s" ostream& operator<< (ostream& os, const char* s); If you want to print the start address of the character array, one way is to:
// std::hex is optional. It prints the address in hexadecimal format. cout<< std::hex << static_cast<void*>(&s[0]) << std::endl; This will instead use another overload of operator<< :
// prints the value of a pointer itself ostream& operator<< (const void* val); You are running into the internals of how C (and C++) handle strings (not std::string for C++).
A string is referenced by a pointer to it's first character. Here's code that shows this:
char *ptr; ptr = "hello\n"; printf("%s\n", ptr); ptr++; printf("%s\n", ptr); argv is defined to specifically contain "pointers to strings", the description of the character set says that the null character "is used to terminate a character string" etc etc.
char*overload for operator<<which prints the whole c-string.