working on arrays, when I noticed that an array of ints didn't behave the same way as an array of chars. What is happening here? I was expecting the same result when printing the tab of chars as I get when printing the table of ints (i.e. memory address to first element)
1 2 3 4
char tab[] = {'a', 'b', 'c', 'd'};
cout << tab; //prints abcd
int tab2[] = {2, 3};
cout << tab2; //prints the memory address of the first element.
As @salem c said, you are a tad lucky with your char array: the stream would have been expecting a null-terminated string ("c-string") and your code relies on the next memory address containing a null character: it might have contained anything.
Try
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int main()
{
char tab[] = {'a', 'b', 'c', 'd'};
for ( auto e : tab ) cout << e;
cout << '\n';
int tab2[] = { 2, 3 };
for ( auto e : tab2 ) cout << e;
cout << '\n';
}
It's unfortunate, but an array of characters with a null character '\0' at the end is how strings were handled in C, and it's still used a lot in C++ even though it has got the std::string class, so for convenience the << operator has been overloaded for char* to instead treat it as a string.
There is no difference between an array of characters compared to any other array from the language point of view. The difference is how the standard library (in this case the << operator) handles it.
So use it like normal, except when you want to print the address of one of its elements, then you can cast it to void* before printing.
You can see it represents something called "NUL". Right at the start. The first 32 such, from "NUL" to "US" are not meant to be seen. Not meant for printing out.
Note that the '0' character is represented by the number 48. If the memory at location (prt+4) contained the number 48, and you sent that to cout as a char, you'd see '0' on the screen. The char '0' is not the same as the number 0. In memory the char '0' is represented as 48.