This declaration of an array of characters
char my_string[] = "Hello";
is equivalent to the following declaration
char my_string[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
That is the elements of the array are initialized by the characters of the string literal including its terminating zero.
Used in expressions arrays with rare exceptions are converted to pointers to their first elements.
For example if you are using the sizeof operator then an object of an array type is not converted to pointer to its first element. This one of rare exception.
Here is a demonstrative program
#include <iostream>
int main()
{
int my_array[] = { 1, 2, 3 };
char my_string[] = "Hello";
std::cout << "sizeof( my_array ) = " << sizeof( my_array ) << '\n';
std::cout << "sizeof( my_string ) = " << sizeof( my_string ) << '\n';
return 0;
}
Its output is
sizeof( my_array ) = 12
sizeof( my_string ) = 6
But for example when an object of an array type is used as an operand of the operator * then it is converted to pointer to its first element.
Here is another demonstrative program
#include <iostream>
int main()
{
int my_array[] = { 1, 2, 3 };
char my_string[] = "Hello";
std::cout << "*my_array = " << *my_array << '\n';
std::cout << "*my_string = " << *my_string << '\n';
return 0;
}
The program output is
*my_array = 1
*my_string = H
In the C++ Standard there is defined the overloaded operator <<
to output strings (sequence of characters terminated by the zero character) pointed to by a pointer to char.
So if you will write
std::cout << my_string << '\n';
then in the call of this operator << the character array is implicitly converted to pointer to its first element and the pointed string is outputted.
For integer arrays the operator << is defined such a way that it just outputs the address of the array that is the address of its first element.
Here is a demonstrative program.
#include <iostream>
int main()
{
int my_array[] = { 1, 2, 3 };
char my_string[] = "Hello";
std::cout << my_array << '\n';
std::cout << my_string << '\n';
return 0;
}
Its output might look like
0x7ffdcfe094e4
Hello
If you want that for a character array there would be selected the overloaded operator << that outputs the address of the array then you should cast the array (that is implicitly converted to pointer to its first element) to the type void *
.
Here is one more demonstrative program.
#include <iostream>
int main()
{
int my_array[] = { 1, 2, 3 };
char my_string[] = "Hello";
std::cout << my_array << '\n';
std::cout << static_cast<void *>( my_string ) << '\n';
return 0;
}
Its output might be
0x7ffef7ac0104
0x7ffef7ac0112