A question about const char and string literals

Hi, Korean c++ learner again. I feel like I'm getting a lot of help from this community after all. Also, a huge thanks to that last answer about the stream extractor >>.

Since I was now studying pointers, I looked up some tutorials available at this website. I came across the chapter about the relationship between string literals and pointers.
------------------------------

const char *hello = "hello";

------------------------------
So typing the code above would make the pointer <hello> point to 6 memory locations in which the string literal is stored. I understood that, but then I got a question.
------------------------------

cout << hello << endl;

------------------------------
After typing this code, I got 'hello' as a result, when I was expecting to get the address of the memory location where <h> is stored.
------------------------------

int *array = new int [5];
cout << array << endl;

------------------------------
Just like making an array and printing the name of it would give me the address of the memory in which it's located.

Could anybody please explain why I'm getting the results above?
Last edited on
Hi

std::cout has a an overload that deals with const char* that prints the C string as expected.

Those overloads are described in:

http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/ has
ostream& operator<< (void* val);

http://www.cplusplus.com/reference/ostream/ostream/operator-free/ has
1
2
3
ostream& operator<< (ostream& os, const char* s);
ostream& operator<< (ostream& os, const signed char* s);
ostream& operator<< (ostream& os, const unsigned char* s);



There is exact match for const char*
There is no match for int*, but conversion of int* into void* is possible.


const char *hello = "hello";
So typing the code above would make the pointer <hello> point to 6 memory locations in which the string literal is stored.

Not quite. The pointer points to a char, not to multiple. The char* has address of one char, one memory location. The address of the 'h'.
Just further:

The printing of a C string works because it is null terminated. Even though std::cout starts with a pointer to the first character, it can increment that pointer, dereference that pointer each time to obtain the char, then continue until the null is reached.
Topic archived. No new replies allowed.