I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers.
int main() {
int arr[10] = {1,2,3};
char arr2[10] = {'c','i','a','o','\0'};
cout << arr << endl;
cout << arr2 << endl;
}
However when I run this, arr outputs the address of the first element of the array of ints (as expected) but arr2 doesn't output the address of the first element of the array of chars; it actually prints "ciao".
What is it that I'm missing or that I haven't learned yet about this?
-
There is a standard overload for char* that outputs a NUL terminated string.
-
Because cout's operator << is overloaded for char* to output strings, and arr2 matches that.
If you want the address, try casting the character array as a void pointer.
-
It's the operator<< that is overloaded for
const void*
and forconst char*
. Your char array is converted toconst char*
and passed to that overload, because it fits better than toconst void*
. The int array, however, is converted toconst void*
and passed to that version. The version of operator<< takingconst void*
just outputs the address. The version taking theconst char*
actually treats it like a C-string and outputs every character until the terminating null character. If you don't want that, convert your char array toconst void*
explicitly when passing it to operator<<:cout << static_cast<const void*>(arr2) << endl;
-
While casting is probably a more meaningful approach, you could also use the addressof operator:
cout << &arr2 << endl;
D.Shawley : Probably want `&arr2[0]` instead of `&arr2` hereRob Kennedy : Those are the same addresses, Shawley.Mystic : An array in C/C++ is just a series of memory locations. So the address of array is the address of the first element. Wonder why this was voted downMSalters : Mostly because it doesn't explain the idea - a char[10]* does not convert to char*.
0 comments:
Post a Comment