gpt4 book ai didi

c - C 中链表上​​的双指针

转载 作者:行者123 更新时间:2023-11-30 18:46:37 26 4
gpt4 key购买 nike

在简单链表中,为什么插入节点时要传递双指针?与第二个代码有什么区别?

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
}

如您所见,对 foo 内的 n 所做的更改不会改变 bar 内的 n .

如果您确实希望更改 bar 内的 n 又如何呢?

您可以在此处传递一个指向 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);

关于c - C 中链表上​​的双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771880/

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