help with const char's and string literals!

I am completely stuck in comprehending Sections [10.2] String Literals revisited and [10.3] Initializing arrays of character pointers in Accelerated C++...

Suppose I have an int array and char array:

int intArray[] = {1,2,3,4,5};
char charArray[] = {'h','e','l','l','o','\0'};

by default, the array returns the memory location of the first element, so:

cout << intArray // memory address of first element
cout << *intArray // dereferenced memory address of first element; 1 

BUT when you do it with the character array, its not the same:

cout << charArray // hello
cout << *charArray // h 

I know that the string literal "hello" is the same thing as a char array with a null character added to the end. Does that have anything to do with why charArray returns hello?


I tried searching using different words and I got this thread:

This seems to imply that character arrays are treated differently than all other types of arrays for their return value, yet still are the same for their dereferenced return value?


I guess I might as well post my follow-up question while I'm at it. It was actually this part that completely blows me away:

char *p_Char = "this is a string literal";

What is going on here? It seems to me like its trying to cram a string literal into a char, yet the compiler only gives me this message:

"Conversion from string literal to 'char *' is deprecated

To make things more confusing, slapping a const in front of it makes the warning go away. ??? I thought const was just to let the compiler know that the values won't be changed?

when I cout the p_Char as is, then for some reason it returns the entire string literal. When I cout *p_Char, it returns the first character, which makes more sense to me since a dereferenced character pointer should return a character.

Please help me out since I've been stuck on this part for the last 3 days and I can't figure it out!
Last edited on
It's not that char arrays are different. It's just that the operator<< is overloaded for char* to work in this way. It is very convenient that it works that way because if it didn't then std::cout << "hello"; would print a memory address instead of printing "hello".

char *p_Char = "this is a string literal";
What happens here is that "this is a string literal" gives you a char array of size 25. As you know an array decays to a pointer to the first element in the array in many cases. That is what happens here. p_Char will point to the first element in the array. The array is actually read-only so you should have used const. That's why you got the warning (In C++11 it's an error).
Last edited on
Topic archived. No new replies allowed.