This code:

int array1[5] = {1, 30, 90, 40, 3}; 
	char array2[] = {125, '}'};
	cout << array1 << endl;
	cout << array1[0] << endl;
	cout << array1[1] << endl;
	cout << array1[2] << endl;
	cout << array1[3] << endl;
	cout << array1[4] << endl;
	cout << array2 << endl;

gives me these results:

0x7fff5fbff450
1
30
90
40
3
}}

What I'm wondering is: Why does array2 output all the elements of the array in order (line10), but when I try it for array1 it gives me an odd code instead of each number in order (line 4). Just wondered.

Recommended Answers

All 3 Replies

Firstly you shouldn't cout array1 and then cout all of it's elements, it doesn't make sense, take line 4 out.

The "odd code" is the memory address of the first element of the array, since that's what your accessing by giving the name of the array. In the second case, you're using a char array, which is treated in a special way, so that you can do something like:

char s[6] = "Hello";
std::cout << s << std::endl;

This important thing here is that the char array is one byte longer than the string that you're trying to store (to hold a terminating \0 character that gets tagged on automatically for you). By building the char array "manually", you don't have the terminating character, so cout doesn't really know when to stop. For example, for me, your code outputtted random characters at the end of the array, like this: }}5�& Hope that makes sense :o)

Thanks, that makes sense. I know I'm not 'supposed' to use it like that - I've just been code-diving to kinda kick the tires a little so I can feel out how these things work and don't work. Just want to know my boundaries - thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.