c - C中链表上的双指针
问题描述
在一个简单的链表中,为什么在插入节点时要传递一个双指针?与第二个代码有什么区别?
void push(struct node **headRef, int data);
void push(struct node *head, int data);
解决方案
C 函数调用总是传递参数的值。当您在函数内部时,您可以将来自调用者的值的副本放在新变量中。
您可以在函数内更改这些副本的值,但调用者拥有的值将保持不变。
例子:
void foo(int n)
{
n = 1;
printf("In foo: %d\n", n); // Will print 1
}
void bar()
{
int n = 42;
printf("In bar: %d\n", n); // Will print 42
foo(n);
printf("Back in bar: %d\n", n); // Will still print 42
}
如您所见,对n
insidefoo
所做的更改不会更改n
inside bar
。
那么,如果你真的想改变n
内心bar
呢?
那是你而不是传递n
一个指向.n
喜欢:
void foo(int *n) // Note the *
{
*n = 1;
printf("In foo: %d\n", *n); // Will print 1
}
void bar()
{
int n = 42;
printf("In bar: %d\n", n); // Will print 42
foo(&n); // Note the & to get a pointer to n
printf("Back in bar: %d\n", n); // Will now print 1
}
这也是您的代码行之间的区别:
void pushA(struct node **headRef, int data);
void pushB(struct node *head, int data);
struct node *head = NULL;
pushA(&head, 42); // head may be changed after this call
pushB(head, 42); // head is unchanged after this call
第一个版本可能是您想要的,即在将新元素推送到列表时,您希望将元素插入到前面,因此需要更改 head 的值。
另一种方法是让函数返回一个指向新头的指针:
struct node* push(struct node *head, int data);
struct node *head = NULL;
head = push(head, 42);
推荐阅读
- logging - Spring Cloud Gateway - 禁用特定路由的日志
- javascript - Ubuntu 20.04 上 Node JS 脚本执行缓慢
- c# - 如何在会话中使用 linq 进行过滤?
- c# - 具有主子关系的 PGSQL 中的批量插入
- keycloak - 钥匙斗篷中的 acr 替代品
- typescript - LokiJS saveDatabase 到持久性问题
- java - mvn 站点插件错误 TEXT 必须紧跟 END_TAG 而不是 START_TAG
- android - 如何在 Android 的图库中以每 5 秒的时间块保存自定义相机视频流
- c - 生成文件项目
- database - Clickhouse - OOM - Clickhouse数据导入功能执行时,程序被系统杀死