繁体   English   中英

在链表中取消引用指针

[英]Ddereferencing a pointer in linked list

我在tail->next=(list)malloc(sizeof(node))遇到错误。 有人可以告诉我为什么吗? 该代码已在NPTEL视频之一中教授,并且可以正常运行。

tail->next=(list)malloc(sizeof(node))有什么问题吗?

#include<stdio.h>
#include<stdlib.h>

main(){
    int choice,dat;

    typedef struct {
        int data;
        struct node* next; //pointer to a node
    }node;

    typedef  node* list;

    list head,tail;

    head=tail=NULL;

    printf("Enter Data? (1/0)\n");
    scanf("%d",&choice);

    if(choice==1)
    {
        printf("Give Data?\n");
        scanf("%d",&dat);
        tail=(list)malloc(sizeof(node));
        tail->data=dat;
        tail->next=NULL;
        head=tail;

        printf("Enter Data? (1/0)\n");
        scanf("%d",&choice);        
    }

    while(choice==1){
        printf("Give Data?\n");
        scanf("%d",&dat);

        tail->next=(list)malloc(sizeof(node));//showing error
        tail->next->data=dat;
        tail->next->next=NULL;
        tail=tail->next;
    }

    tail=head;

    while(tail!=NULL){
        printf("%d",tail->data);
        tail=tail->next;
    }
}

为了使代码成功编译,您需要按以下方式声明节点类型。

typedef struct Node{
    int data;
    struct Node* next; //pointer to a node
}node;

这种额外命名的原因是由于直到以typedef开头的语句结束才将节点视为声明的节点。 这就是为什么您还需要命名结构体以便能够在其内部声明一个指向其自身类型的指针的原因。

另外,当您尝试提到的有问题的行时,tail可能等于NULL:

tail->next=(list)malloc(sizeof(node));//showing error

除非输入的值在第一个if语句为1之前通过scanf读取到变量选择中,否则当第一个while循环开始并尝试访问(即,以便分配所分配空间的地址)tail时,tail将为NULL。 next 等效于解引用NULL地址,然后尝试访问next字段,从而导致段冲突。

您的问题在这里:

typedef struct {
    int data;
    struct node* next; // <-- problem
} node;

您正将struct node声明为与(匿名)struct node不同的类型。

您可以通过为匿名结构提供name node来解决此问题,以便可以在定义中引用它:

typedef struct node {
    int data;
    struct node* next;
} node;

现在只有一个名为node类型。


另外,您的main功能缺少返回类型。 它应该是:

int main() {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM