【问题标题】:Understanding the operation of pointers in C++了解C++中指针的操作
【发布时间】:2015-09-24 07:51:51
【问题描述】:

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

假设我的结构如下:

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

我还有一个功能如下:

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

我的问题:

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

  2. 函数中*&是什么意思?我注意到在插入的链表实现中(在我看到的教程中)'*&' 被使用而不是 '*' 为什么会这样?

如果这个问题很愚蠢,我深表歉意,但我很难理解这一点。谢谢。

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

【问题讨论】:

  • 如果不查看使用该结构的代码,我们如何知道n2 指向的内容?
  • 如果我不得不猜测,n1 可能是指向列表中下一个兄弟node 的指针,而n2 是指向子nodes 的指针的动态数组。
  • node* 指向nodenode** 指向node*node*& 是对指向节点的指针的引用。

标签: c++ pointers data-structures


【解决方案1】:
  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;

使用'*'和'**'有什么区别?

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

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

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

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

我注意到在插入的链表实现中(在我看到的教程中)'*&' 被使用,而不仅仅是'*',为什么会这样?

使用引用,以便函数可以修改被引用的调用者变量,例如:

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 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多