[Solved] In char x[10]=”hello” , why cout


It prints “Hello” because operator << has an overload for const char* (which is what you’re passing if you pass x) that prints out a single char and moves to the next char until a NUL-character is found. “Hello” has a compiled-added NUL-character at the end, so your string is actually “Hello\0”.

To get the address you can cast it to a void* to remove the overload of const char*:

reinterpret_cast<const void*>(x)

Why is this legal, Aren’t pointers supposed to store only address?

Yes, that’s exactly what ptr is storing. When you assign a pointer to “Hello” which is a const char[] the ptr will point to [0] of that array. Note though that in this case a conversion first has to be made from const char* to char* which has been deprecated for years and is since C++11 illegal because trying to edit the pointee through this char* will lead to undefined behaviour. Some compilers still allow this though while really they should emit an error.

2

solved In char x[10]=”hello” , why cout<