C ++ ampersand operator with char arrays

I was just playing with pointers and arrays when I was confused with this code that I tested.

#include <iostream> using namespace std; int main(void) { char a[] = "hello"; cout << &a[0] << endl; char b[] = {'h', 'e', 'l', 'l', 'o', '\0'}; cout << &b[0] << endl; int c[] = {1, 2, 3}; cout << &c[0] << endl; return 0; } 

I expected this to print three addresses (from [0], b [0] and c [0]). But the result:

 hello hello 0x7fff1f4ce780 

Why is this for the first two cases with char, '&' gives a whole line, or am I missing something here?

+6
source share
1 answer

Because cout operator << prints the line if you pass it the char* as parameter, which is &a[0] . If you want to print the address, you need to explicitly point it to void* :

 cout << static_cast<void*>(&a[0]) << endl; 

or simply

 cout << static_cast<void*>(a) << endl; 
+10
source

Source: https://habr.com/ru/post/947138/


All Articles