【问题标题】:Regarding dereferencing a pointer while using in linked lists关于在链表中使用时取消引用指针
【发布时间】:2022-01-17 22:35:14
【问题描述】:

在这里,我尝试创建一个链表并创建一个函数,它将任何给定的数字添加到链表的起始位置。

#include <stdio.h>
#include <stdlib.h>
struct Node{
    int data;
    struct Node* next;
};
struct Node* head=NULL;

void Add(int n){
    head=(struct Node*)malloc(sizeof(struct Node));
    head->data=n;
    head->next=NULL;
    return;
}

现在我的疑问是,这里我们将head 定义为数据类型struct Node 的指针变量。在Add函数中,我们已经分配了分配给head指针变量的新内存地址。

但是当我们写head-&gt;data=n的时候,为什么不先解引用head,因为head是一个指针变量,所以它存储地址,并且像存储数据一样存储变量,为什么不应该是@ 987654329@? *head-&gt;next=NULL 类似。

【问题讨论】:

    标签: c pointers dereference


    【解决方案1】:

    不,您需要分两步进行添加。首先创建新节点并对其进行初始化,然后将其链接到列表中。否则你会丢失整个列表,如下图:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct Node{
        int data;
        struct Node* next;
    };
    
    struct Node* head = NULL;
    
    void Add(int n)
    {
    
        // create the node.
        struct Node *node = malloc(sizeof *node);  /* better */
    
        // then initialize it.
        node->data=n;
    
        // now you can link it to the list
        node->next=head; // this must be done before touching header, so we don't lose header's value.
        head = node;
    
    }
    

    顺便说一句,不要强制转换malloc() 返回的值,这会导致您在代码中出现您不希望出现的错误。如果您忘记#include &lt;stdlib.h&gt;,您可能会遇到严重的未定义行为(在 64 位系统中更多,指针和整数具有不同的大小)强制转换告诉编译器您知道自己在做什么,所以您可能会将来自编译器的警告和消息静音,以解决问题。不要这样做,很久以前(从第一版STD-C出版时)就没有必要了

    【讨论】:

      【解决方案2】:

      运算符-&gt; 已经是一个取消引用运算符。 head-&gt;data 等价于(*head).data

      【讨论】:

      • 无需添加“谢谢”评论。经过一段时间后,只需标记答案;可能会有更好的答案。 ;-) 欢迎来到 StackOverflow!您可能想通过tour 了解该网站的运作方式。
      猜你喜欢
      • 2017-11-03
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 2015-12-31
      • 2011-01-24
      • 1970-01-01
      相关资源
      最近更新 更多