我正在尝试对链表进行排序。我对何时使用 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/