理解C++中指针的操作

Understanding the operation of pointers in C++

本文关键字:操作 指针 C++ 理解      更新时间:2023-10-16

我一直在努力理解C++中的指针是如何工作的,我有一些疑问,我希望这里的人能帮助我。

假设我的结构如下:

struct node
{
    int val;
    node *n1;
    node **n2;
};

我还有一个功能如下:

void insertVal(node *&head, node *&last, int num)

我的问题:

  1. n2指向什么?使用'*''**'有什么区别?

  2. 在函数中*&是什么意思?我注意到,在insert的链表实现中(在我看到的一个教程中(使用了'*&',而不仅仅是'*',为什么会出现这种情况?

如果这个问题很傻,我很抱歉,但我很难理解。谢谢

编辑:我简化了结构只是为了理解**的意思。代码在这里:http://www.sanfoundry.com/cpp-program-implement-b-tree/.有人提到**指的是一组节点,我认为这里就是这样。

  1. n2指的是什么

如果没有看到使用它的实际代码,就无法回答这个问题。但是,如果必须猜测的话,它可能是指向子node指针的动态数组的指针,例如:

node *n = new node;
n->val = ...;
n->n1 = ...;
n->n2 = new node*[5];
n->n2[0] = new node;
n->n2[1] = new node;
n->n2[2] = new node;
n->n2[3] = new node;
n->n2[4] = new node;

使用"*"answers"***"有什么区别?

指向node的指针与指向node的指针的指针,例如:

node n;
node *pn = &n;
node **ppn = &pn;
  1. 在函数中,*&指向什么

它是对指针变量(*(的引用(&(。如果你调整参数周围的空白,可能会更容易阅读:

void insertVal(node* &head, node* &last, int num)

我注意到,在insert的链表实现中(在我看到的一个教程中(使用了'*&',而不仅仅是'*',为什么会出现这种情况?

引用被使用,这样被引用的调用方变量可以被函数修改,例如:

void insertVal(node* &head, node* &last, int num)
{
    ...
    // head and last are passed by reference, so any
    // changes made here are reflected in the caller...
    head = ...;
    last = ...;
    ...
}

node *head = ...;
node *last = ...;
...
insertVal(head, last, ...);
// head and last contain new values here ...

否则,在没有&(或第二个*(的情况下,原始指针只是作为副本按值传递,对该副本的任何更改都不会反映在调用方的变量中:

void insertVal(node* head, node* last, int num)
{
    ...
    // head and last are passed by value, so any changes
    // made here are not reflected in the caller...
    head = ...;
    last = ...;
    ...
}

node *head = ...;
node *last = ...;
...
insertVal(head, last, ...);
// head and last still have their original values here ...