[英]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.