c - C函数中的指针到指针;链表

标签 c linked-list dynamic-memory-allocation singly-linked-list

在将其标记为重复之前,我已阅读
In C, what does a variable declaration with two asterisks (**) mean?
I don't understand the implementation of inserting a new node in linked list
我仍然在努力解决双星号的逻辑步骤。我知道在链表中我需要创建一个新节点,为其动态分配空间,然后将新节点重新标记为头。
我只是不明白 &head 和双星号之间的函数的逻辑步骤。这里的双星号指的是什么以及如何实现?

void push(struct node** head_ref, int new_data)
{
    struct node* new_node = (struct node*)malloc(sizeof(struct node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}

push(&head, 2);

最佳答案

由于调用者传递 &head 作为第一个参数,

  • head_ref 等于 &head
  • *head_ref 等于 head

因此,调用 push(&head, 2) 与在调用方中编写代码具有相同的最终效果,如下所示。

/*   struct node **head_ref = &head;   */

struct node *new_node = malloc(sizeof(struct node));
new_node->data = 2;
new_node->next = head;       /*   new_node = (*head_ref) */
head = new_node;             /*    (*head_ref) = new_node */

我已经注释掉了 head_ref 的所有用法,因为它是函数的本地变量,调用者看不到。最后两个语句中的注释显示了等效性。

请注意,我还删除了 malloc() 结果的类型转换,因为这样的事情在 C 中通常被认为是不好的做法。

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

相关文章:

c - 数组结构无法正常工作

c - 在 C 中完成指针转换时,字节会被交换

c++ - Elem 没有命名类型?

java - 我的 SelectionSort 方法不起作用。为什么?

c - 为什么malloc在达到一定阈值之前不分配内存?

c - 如何检查 stdin 缓冲区是否包含一些数据?

c - 哪些可移植性问题与 C 语言中指针的字节级访问相关?

c - 在 C 中反转列表后打印单链表的问题

c - fgets() 与 realloc() 的奇怪行为

c - 动态数组的可变参数函数?