I have this code:
char *array = "test";
cout << &array[0];
The output is test. Why is this working?
I have this code:
char *array = "test";
cout << &array[0];
The output is test. Why is this working?
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.