0

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.

2
  • 1
    a) don't use arrays (prefer std::vector/std::array) b) this is working as intended, the second one calls the char* overload for operator << which prints the whole c-string. Commented Sep 2, 2013 at 0:43
  • Were you looking for the second to print the memory address, one character, or something else? Commented Sep 2, 2013 at 0:46

2 Answers 2

6

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); 
Sign up to request clarification or add additional context in comments.

Comments

0

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); 

6 Comments

Actually, to be more accurate - C has no built-in string construct. This is a feature of the standard C library.
Ash: Simply not true, string literals are a built in construct, 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.
The main function is called by the "C" startup code, which is in a library.
Doesn't even deserve a response.
Actuall, the "C" language is rather bare if you look at the core of it. There no input nor output (open/read/write are function calls, not language statements). Even the main function isn't part of the langauge itself. They are probably part of some standards now that some might consider the same as "the C language"...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.