C++ 指针
创建指针
您从上一章中了解到,我们可以通过使用 & 运算符获得变量的内存地址
实例
#include <iostream>#include <string>using namespace std;int main() {string food = "Pizza";cout << food << "\n";cout << &food << "\n";return 0;}
然而,指针是一个将内存地址存储为其值的变量。
指针变量指向同一类型的数据类型(如 int 或 string),并使用 * 运算符创建。正在使用的变量的地址被分配给指针:
实例
#include <iostream>#include <string>using namespace std;int main() {string food = "Pizza"; // A string variablestring* ptr = &food; // A pointer variable that stores the address of food// Output the value of foodcout << food << "\n";// Output the memory address of foodcout << &food << "\n";// Output the memory address of food with the pointercout << ptr << "\n";return 0;}
实例解释
使用星号 *(string* ptr) 创建一个名为 ptr 的指针变量,该变量指向一个字符串变量。请注意,指针的类型必须与正在使用的变量的类型相匹配。
使用 & 运算符存储名为 food 的变量的内存地址,并将其分配给指针。
现在,ptr 保存 food 的内存地址值。
提示:有三种方法可以声明指针变量,但首选第一种方法:
string* mystring; // Preferredstring *mystring;string * mystring;
解引用
获取内存地址和值
在上一页的示例中,我们使用指针变量获取变量的内存地址(与 & 引用运算符一起使用)。但是,也可以使用 * 运算符(解引用运算符)使用指针来获取变量的值:
#include <iostream>#include <string>using namespace std;int main() {string food = "Pizza"; // Variable declarationstring* ptr = &food; // Pointer declaration// Reference: Output the memory address of food with the pointercout << ptr << "\n";// Dereference: Output the value of food with the pointercout << *ptr << "\n";return 0;}
请注意,*符号在这里可能会令人困惑,因为它在我们的代码中做了两件不同的事情:
- 在声明(string* ptr)中使用时,它会创建一个 指针变量。
- 当不是在声明时,它充当 解引用运算符。
修改指针
还可以更改指针的值。但请注意,这也会改变原始变量的值:
#include <iostream>#include <string>using namespace std;int main() {string food = "Pizza";string* ptr = &food;// Output the value of foodcout << food << "\n";// Output the memory address of foodcout << &food << "\n";// Access the memory address of food and output its valuecout << *ptr << "\n";// Change the value of the pointer*ptr = "Hamburger";// Output the new value of the pointercout << *ptr << "\n";// Output the new value of the food variablecout << food << "\n";return 0;}