c - struct node *head 和 struct node ** head 有什么区别?

标签 c pointers linked-list

我正在尝试对链表进行排序。我对何时使用 struct node*head 以及何时使用 struct node **head 感到困惑,可以同时使用它们来完成实现。

我应该什么时候使用:

void sortedinsert(struct node **head)

什么时候应该使用:

void sortedinsert(struct node *head)

最佳答案

使用这个函数签名:

void changeNode(struct node *head)

您有一个指向节点的指针,因此您可以更改该结构。您不能更改变量头指向的内容。假设 struct node 的定义如下:

struct node
{
    int field1;
    struct node *next;
}

根据给定的函数签名和struct node,考虑以下操作可以改变函数中的结构:

void changeNode(struct node *head)
{
    head->field1 = 7;
    head->next = malloc(sizeof(struct node));
}

C 是按值传递的:当我们将一个变量传递给一个函数时,该函数得到一个副本。这就是我们将指针传递给 struct node 的原因,这样我们就可以更改它,并在函数外部产生这些更改的效果。但是我们仍然只能得到指针本身的副本。所以下面的操作没有用:

void changeNode(struct node *head)
{
    // we're only changing the copy here
    head = malloc(sizeof(struct node));
}

head 的更改不会反射(reflect)在函数外部。为了改变 head 指向的内容,我们必须使用额外的间接级别:

void changeNode(struct node **head)
{
    // now we're changing head
    *head = malloc(sizeof(struct node));

    // alternately, we could also do this:
    *head = NULL;
}

现在对 head 的更改反射(reflect)在 函数之外。

关于c - struct node *head 和 struct node ** head 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12124096/

相关文章:

c - fgets 在我不希望的时候拆分输入字符串

c++ - 为什么指向指针的指针是一个矩阵?

链表的C++继承

c - 重申链表(银行家算法)

C - 有没有办法处理中间有 NULL 字符的字符串

c - 我的代码上下文中的 UndefinedBehaviorSanitizer 是什么

c++ - 如何创建指向结构的指针数组?

java - 混淆Java链表问题的值

简单加密代码的 C 段错误

c++ - 在 C++ 中自初始化为 nullptr 的普通原始指针