【问题标题】:Pointer to Pointer in C function; Linked ListsC函数中指向指针的指针;链表
【发布时间】:2018-07-28 23:44:10
【问题描述】:

在标记为 dup 之前,我已阅读
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);

【问题讨论】:

  • 使用笔和纸。手动执行代码。画图。写出变量的值。
  • 这看起来不像标准的 push 函数 - 它更像是 createAndPush
  • 1.将地址作为指向指针的指针(因为它是一个节点) 2. 创建第二个节点 3. 使新节点指向(旧)头 4. 然后将 new_node 重新标记为头(或第一项在list) 那么由于节点结构的性质,双星号只是双星号?像 struct node ** 基本上是在声明节点的类型和数据类型?
  • 函数调用像赋值一样工作:参数被赋值给参数。我们有head_ref = &head,所以head_ref 指向head
  • @klutt 是的,实际上笔和纸对我有用。泰

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


【解决方案1】:

由于调用者将&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 的所有用法,因为它是函数的局部变量,调用者看不到。最后两个语句中的 cmets 显示了等价性。

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

【讨论】:

  • 谢谢我现在意识到它必须是双星号才能获取地址并获取地址。我认为我遗漏了一些合乎逻辑的步骤,因为它指向未知的东西以准备新节点(尚未创建!)现在我明白了,谢谢大家
【解决方案2】:

确实,为了了解发生了什么,您必须了解指向指针的指针是什么以及遵循运算符* 的含义。 然后你可以按照代码:

void push(struct node** head_ref, int new_data)

函数push 有两个参数:指向指针的指针和int 值。

head 是指向struct node 类型变量的指针

struct node* head;

要正确调用push,您必须获取head 指针的地址。 它是通过使用& 运算符来完成的。那么&head就是指针的地址。

struct node **head_ref = &head;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多