0

I have this code:

char *array = "test";
cout << &array[0];

The output is test. Why is this working?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • `char *array = "test";` should fail to compile. The code should be `char const* array = "test";` – Eljay May 05 '21 at 23:10

1 Answers1

1

array[0] is a single char.

&array[0] is a pointer to that single char. Its type is char*. And that type is used to mean "pointer to first char of null-terminated string". Which is how the stream output operator << treats it.

If you want to print the pointer you need to cast it:

cout << reinterpret_cast<void*>(&array[0)];

With that said, the definition

char *array = "test";

is wrong. Literal strings like "test" are constant arrays of characters (including the null-terminator).

So pointers needs to be const qualified:

const char *array = "test";

And the cast need to include a const as well.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621