![](/img/trans.png)
[英]I am trying to insert a new starting/head node in a linked list...The commented out function doesn't work while the one below it does the job
[英]Why does sending **head to a function work while reversing an SLL and *head doesn't in C?
我正在使用 Apple Clang 11.00 编译我的代码以反转链接列表。 我起初使用此代码但它不起作用:
void reverseSLL(node *head)
{
node *cur, *next, *prev;
cur = head;
prev = next = NULL;
if (head == NULL) {
printf("SLL does not Exist.\n");
return;
}
while (cur != NULL) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
head = prev;
}
然后我切换到这个并且它起作用了:
void reverseSLL(node **head)
{
node *cur, *next, *prev;
cur = *head;
prev = next = NULL;
if (*head == NULL) {
printf("SLL does not Exist.\n");
return;
}
while (cur != NULL) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
*head = prev;
}
我不明白为什么会这样。 有人可以帮忙吗?
C 中函数的参数是按值传递的,这意味着一旦函数返回,对函数体内参数值所做的更改就不起作用。 一个简单的例子:
void foo(int a)
{
a += 10;
}
int main()
{
int b = 0;
printf("before: %d\n", b);
foo(b);
printf("after: %d\n", b);
return 0;
}
这将打印:
before: 0
after: 0
如果您希望调用函数(在本例中为main
)查看更新后的值,您必须传递一个指向int
的指针(您也可以返回更新后的值,但我们将在此处忽略):
void foo(int *a)
{
*a += 10;
}
int main()
{
int b = 0;
printf("before: %d\n", b);
foo(&b); /* Note that we are taking the address of 'b' here */
printf("after: %d\n", b);
return 0;
}
在这种情况下,我们的输出将是:
before: 0
after: 10
传递指针也不例外。 对函数中的指针进行更改不会在调用函数中更改它,因此您必须将指针传递给该指针。 这就是您的第二个代码示例有效的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.