In the example from the previous page, we used the pointer variable to get the memory address of a variable (used together with the &
reference operator). However, you can also use the pointer to get the value of the variable, by using the *
operator (the dereference operator):
string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration
// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
Try it Yourself »
Note that the *
sign can be confusing here, as it does two different things in our code:
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!