So recently, I watched a video where it said that when I defined an array of integers for example
int my_array[] = {1,2,3};
and I printed my_array cout << my_array;
then I would get the address of the first integer in memory, but when we define an array of characters like
char my_string[] = "Hello";
then when I try to print my_string cout << my_string
it returns Hello
, similarly with pointers when we define a pointer to characters
char mystring[] = "HELLO";
char *my = mystring;
cout << my << endl;//HELLO
and we try to print the pointer variable it returns the string.
Now I've read this article and I read that the string takes the memory address with him. But I still can't figure out why they are not the same and why an array of chars prints the string literal and the int array prints the address of the first one.
Thanks in advance.
why an array of chars returns the string literal and the int array returns the address of the first one.
I assume the word "returns" is meant to "print".
Because the non-member std::ostream::operator<<(ostream&, const char *)
overload iterates over the memory the char*
pointer points to and prints the content of it, while there is no std::ostream::operator<<(int*)
overload, so int*
is casted to const void*
and std::ostream::operator<<(const void*)
overload is used to print the value, and that function prints the value of the pointer.
You can still print the value of the pointer to string by casting it manually:
cout << static_cast<void*>(my_string) << endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With