为什么有人需要指针指针?

Cel*_*tas 3 c++ assembly pointers

例如,为什么需要char **myVariable;?如果一个指针只是内存中的一个地址,那么如果它是一个指向带有指向char地址的指针的地址的指针,而不仅仅是指向带有char的地址的指针,它会产生什么区别?

在组装中不会这样

LDR R3, =myVariable
LDR R2, =[R3]
LDR R1, =[R2]
LDR R0, =[R1]
Run Code Online (Sandbox Code Playgroud)

单个指针的位置

LDR R1, =myVariable
LDR R0, =[R1]
Run Code Online (Sandbox Code Playgroud)

现在R0持有价值?显然这种方式更快.

som*_*ley 11

如果要通过函数修改指针的值,则必须通过引用将该指针的地址传递给函数.因此,您需要指针指针作为参数.

示例:

int main()
{
  int num=0;
  int *p = #
  // This function passes the pointer by value. 
  //So when function returns, *p points to same place
  fn(p);

  // This function will actually change where the pointer points to as 
  // it was passed by reference
  fn2(&p);
}
void fn(int *ptr)
{
    static int i=1;
    ptr = &i;
}
void fn2(int **ptr)
{
    static int j=1;
    *ptr = &j;
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然引用会更好地用于此目的,因为我们正在谈论C++.:P (5认同)

Lin*_*cer 10

好吧,如果你有一个指针表,指向该表的指针将具有"指向指针"的类型.