gpt4 book ai didi

c++ - 理解C++中指针的操作

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:52:30 25 4
gpt4 key购买 nike

我一直在努力理解 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/ .有人提到 ** 指的是节点数组,我认为这里就是这种情况。

最佳答案

  1. What does n2 point to?

如果没有看到使用它的实际代码,就无法回答这个问题。但是,如果我不得不猜测的话,它可能是一个指向子 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;

What is the difference between using '*' and '**'?

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

node n;
node *pn = &n;
node **ppn = &pn;
  1. In the function what does *& point to?

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

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

I have noticed that in a linked list implementation for insert (in a tutorial I saw) '*&' was used instead of just '*' why is this the case?

引用是为了让函数可以修改被引用的调用者变量,例如:

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

否则,如果没有 &(或第二个 *),原始指针只是作为拷贝按值传递,并且对该拷贝的任何更改都不会反射(reflect)出来在调用者的变量中:

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

关于c++ - 理解C++中指针的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31258177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com