0

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!

  • It looks like the address of the first element of the array `arr` converted from the array. – MikeCAT Jun 19 '21 at 04:31
  • The array decays into a pointer, and that pointer gets printed. So, yes, it's the address of the array's first element. Now, if that had been a `char` array then the array's contents would have been printed as a zero terminated string, because `char` pointers get special treatment by streams. – Etienne de Martel Jun 19 '21 at 04:33
  • 1
    Does this answer your question? [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) – rawrex Jun 19 '21 at 04:33

1 Answers1

5

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326