理解C++中指针的操作
Understanding the operation of pointers in C++
我一直在努力理解C++中的指针是如何工作的,我有一些疑问,我希望这里的人能帮助我。
假设我的结构如下:
struct node
{
int val;
node *n1;
node **n2;
};
我还有一个功能如下:
void insertVal(node *&head, node *&last, int num)
我的问题:
n2
指向什么?使用'*'
和'**'
有什么区别?在函数中
*&
是什么意思?我注意到,在insert的链表实现中(在我看到的一个教程中(使用了'*&'
,而不仅仅是'*'
,为什么会出现这种情况?
如果这个问题很傻,我很抱歉,但我很难理解。谢谢
编辑:我简化了结构只是为了理解**的意思。代码在这里:http://www.sanfoundry.com/cpp-program-implement-b-tree/.有人提到**指的是一组节点,我认为这里就是这样。
- 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;
- 在函数中,
*&
指向什么
它是对指针变量(*
(的引用(&
(。如果你调整参数周围的空白,可能会更容易阅读:
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 ...
相关文章:
- 迭代器的指针操作问题
- 我试图了解在异或操作后指针变量正在更改
- 通过浮点指针操作字节向量
- 使用 XOR 操作仅使用 2 个指针反转链表
- 为什么指针在由后增量比较器操作时行为不同?
- 指针 OOP 操作
- C++数组指针上的删除操作
- 如何有效地使用 std::async 对指针数组执行操作
- 为什么在执行增量操作之前分配指针值
- 是否可以使用C++函数指针,如 C# 的操作?
- 共享指针,C 版本的原子操作
- 普通指针,连同通常的操作 & 和 *,是 monad 吗?
- 双指针 **src 和操作 (*(*src)++ = reg_offset)
- 调用向量内的函数指针不执行任何操作
- 调用 vector.erase() 函数时指针操作无效错误
- 即使在单线程程序中,共享指针是否在引用计数中使用原子操作
- C 弦乐操作用指针,中间为空
- 尝试仅通过操作指针对链表进行排序
- 在类内部操作指针
- 仅通过操作指针交换链表中的相邻节点