简体   繁体   中英

Why this C++ code works the way it works?

# include <iostream>
using namespace std;

int main(void)
{
     char *name = "Stack overflow";

     cout << *&name << endl;
     cout << &*name << endl;    // I don't understand why this works

     return 0;
 }

I understand how the first "cout" statement works but unable to understand why and how the second one works.

& and * are opposite operations. The first one takes the address of the array (adding one level of indirection) and then dereferences it (removing one level of indirection). The second dereferences the pointer (removing one level of indirection) and then takes the address of the result (adding one). Either way, you get back to the same value.

Just like 4 / 2 * 2 is the same as 4 * 2 / 2, or just like taking a step back and then forward leaves you at the same place as taking a step forward and then backward.

To understand how the second statement works substitute it

cout << &*name << endl;

for

cout << &name[0] << endl;

because *name and name[0] are equivalent and return reference to (lvalue) the first character of the string literal pointed by name.

The last statement is equivalent to

cout << name << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM