-2

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.

  • Doesn't that Asterisk symbol stand for pointer?
  • If it is a pointer, how is it possible for us to assign a value other than the address value?
  • Shouldn't the top output be at the bottom and the bottom output at the top?
  • `Doesn't that Asterisk symbol stand for pointer?` Yes. `If it is a pointer, how is it possible for us to assign a value other than the address value?` Huh? – tkausl Jul 02 '22 at 09:24
  • `str` is a pointer to the first element of an array of `const wchar_t`. `T* p = some_array;` is equivalent to `T* p = &some_array[0];`. You should probably get yourself a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Jul 02 '22 at 09:28
  • 1
    Yes it is a pointer. Normally when we write, ehr no I don't... I always try to minimize the use of (raw) pointers in C++. For strings I use std::string (or std::string_view) for constant strings I use `static constexpr std::wstring{L"This is a simple text"};`. (C++20, wide character string). More pointers on pointers use can be found in this document : Guidelines/CppCoreGuidelines (have a look at std::unique_ptr) – Pepijn Kramer Jul 02 '22 at 09:29

1 Answers1

0

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).

fabian
  • 80,457
  • 12
  • 86
  • 114