Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between char[] and int[] [duplicate]

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.

like image 781
Alex Avatar asked Dec 07 '22 10:12

Alex


1 Answers

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;
like image 132
KamilCuk Avatar answered Dec 28 '22 01:12

KamilCuk