C语言中\*&和\*\*&的含义

新手上路,请多包涵

我在函数声明中多次找到这些符号,但我不知道它们是什么意思。

例子:

 void raccogli_dati(double **& V, double **p, int N) {
  int ultimo = 3;
  V = new double * [N/2];
  for(int i=0; i < N/2; i++) {
    V[i] = new double[N/2], std :: clog << "digita " << N/2 - i
                 << " valori per la parte superiore della matrice V: ";
    for(int j=i; j < N/2; j++)
      std :: cin >> V[i][j], p[ultimo++][0] = (V[i][j] /= sqrt(p[i][0]*p[j][0]));
  }
  for(int i=1; i < N/2; i++)
    for(int j=0; j < i; j++)
       V[i][j] = V[j][i];
}

原文由 sdffadsf 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 598
2 个回答

那是通过引用获取参数。因此,在第一种情况下,您通过引用获取指针参数,因此您对指针值所做的任何修改都会反映在函数之外。第二个与第一个相似,唯一的区别是它是一个双指针。看这个例子:

 void pass_by_value(int* p)
{
    //Allocate memory for int and store the address in p
    p = new int;
}

void pass_by_reference(int*& p)
{
    p = new int;
}

int main()
{
    int* p1 = NULL;
    int* p2 = NULL;

    pass_by_value(p1); //p1 will still be NULL after this call
    pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory

    return 0;
}

原文由 Naveen 发布,翻译遵循 CC BY-SA 3.0 许可协议

*& 表示通过引用接收指针。这意味着它是传递参数的别名。因此,它会影响传递参数。

 #include <iostream>
using namespace std;

void foo(int *ptr)
{
    ptr = new int(50);    // Modifying the pointer to point to a different location
    cout << "In foo:\t" << *ptr << "\n";
    delete ptr ;
}

void bar(int *& ptr)
{
    ptr = new int(80);    // Modifying the pointer to point to a different location
    cout << "In bar:\t" << *ptr << "\n";
    // Deleting the pointer will result the actual passed parameter dangling
}
int main()
{
    int temp = 100 ;
    int *p = &temp ;

    cout << "Before foo:\t" << *p << "\n";
    foo(p) ;
    cout << "After foo:\t" << *p << "\n";

    cout << "Before bar:\t" << *p << "\n";
    bar(p) ;
    cout << "After bar:\t" << *p << "\n";

    delete p;

    return 0;
}

输出:

 Before foo: 100
In foo: 50
After foo:  100
Before bar: 100
In bar: 80
After bar:  80

原文由 Mahesh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题