string literals

I'm a bit baffled by the output from the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int main() {

	int myints[] = { 1,2,3,4,5,6,7 };

	char hello[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

	cout << hello << myints;
	
	return 0;
}


Output: Hello0xbffe48e0

Both myints and hello are arrays, and so as I understand it, their names should be pointers to the first element of an array, so I was expecting to get nonsence in both cases. Is this just my implementation being 'nice' towards hello here, or is this standard behaviour? I read that hello should be synonymous with the string literal "Hello", but this doesn't make sense if it is an array.

Cheers.
hello is a char*. When you do cout << char*, a null terminated string to which hello points is printed. myints is an int*. When you do cout << with any pointer which is not char*, the address of that pointer is printed in hexadecimal.

When you write cout << "Hello", compiler sees it as cout << a_pointer_to_a_null_terminated_const_string_that_says_Hello, so it really is the same thing. The use of string literals in a line such as char hello[] = "Hello" is an entirely unrelated case.
Thanks, hamsterman.

I think I see now: so passing a pointer_to_a_null_terminated_array_containing_chars to cout << is is treated in a special way compared to passing other pointers.

When you say
The use of string literals in a line such as char hello[] = "Hello" is an entirely unrelated case.


I'm a little confused, because my book (Accelerated C++) says that my hello has exactly the same meaning as the string literal "Hello", except, of course that they are different objects in the computer's memory.
Note that cout << doesn't know whether that string in null terminated. It treats all char* that way. If you removed '\0' from your hello, you'd see some garbage.

char hello[] = "Hello"; is just syntactic sugar for char hello[] = {'H', 'e', .... In this case "Hello" does not behave like a normal pointer. In all other cases, it does.
Many thanks for your help, hamsterman. I understand this now.
Topic archived. No new replies allowed.