sudo_cHarG3
sudo_cHarG3

Reputation: 1

What is the value we get on printing an array in cpp?

I'm a beginner to c++, I wrote this in my code:

int *ptr;
int arr[4] = {1, 2, 3, 4};

cout << arr << endl;

This outputs to '0x61ff00'. What does the value mean ? Thanks!

Upvotes: 0

Views: 96

Answers (1)

eerorika
eerorika

Reputation: 238401

There is no standard overload for arrays. There is however an overload for const void*. The array decays to a pointer to first element, which further implicitly converts to const void*. The result is an implementation defined textual representation of the address that is the value of the const void* object.

Memory addresses are essentially numbers. 0x is a prefix for hexadecimal numbers.


Following doesn't apply to the example, but does apply to some other arrays: If the array element is char, then the behaviour of the character stream is different, because there is an overload for const char*. In that case, the behaviour is to treat the array as a null terminated string, and the result is the string contained within the array. String literals are null terminated arrays of char.

Example:

std::cout << "Hello, World!";

Output:

Hello, World!

If the array doesn't contain the null terminator, then the behaviour of the program is undefined. Don't ever insert such array into a character stream.

Upvotes: 5

Related Questions