c++pointerswchar-t

Is " const wchar_t* " a pointer?


Normally when we write:

int a = 10;
int* ptr = &a;
std::cout << *ptr;

Code output is:

> 10

But when I write this:

const wchar_t* str = L"This is a simple text!";
std::wcout << str << std::endl;
std::wcout << &str << std::endl;

Code output is:

> This is a simple text!
> 012FFC0C

So this makes me confused.


Solution

  • L"This is a simple text!" is an array of type const wchar_t[23] containing all the string characters plus a terminating 0 char. Arrays can decay in which case they turn into a pointer to the first element in the array which is what happens in

    const wchar_t* str = L"This is a simple text!";
    

    std::wout can be used with a << operator that takes such a null terminated character as second operand; this operator prints the string.

    The second print simply prints the address of the pointer, since there is no overload for the << operator handling an argument of type const wchar_t** differently to arbitrary pointer types (except for some specific pointer types as seen in the first print).