C++ 指向指针(多级间接寻址)



指向指针的指针是一种多级间接寻址或指针链。通常,指针包含变量的地址。当我们定义指向指针的指针时,第一个指针包含第二个指针的地址,第二个指针指向包含实际值的位置,如下所示。

C++ Pointer to Pointer

指向指针的指针变量必须声明为这种类型。这是通过在其名称前面添加一个额外的星号来完成的。例如,以下是声明指向 int 类型指针的指针的声明:

int **var;

当目标值由指向指针的指针间接指向时,访问该值需要两次应用星号运算符,如下面的示例所示:

#include <iostream>
 
using namespace std;
 
int main () {
   int  var;
   int  *ptr;
   int  **pptr;

   var = 3000;

   // take the address of var
   ptr = &var;

   // take the address of ptr using address of operator &
   pptr = &ptr;

   // take the value using pptr
   cout << "Value of var :" << var << endl;
   cout << "Value available at *ptr :" << *ptr << endl;
   cout << "Value available at **pptr :" << **pptr << endl;

   return 0;
}

编译并执行上述代码后,将产生以下结果:

Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000
cpp_pointers.htm
广告
© . All rights reserved.