OK,這是在C內存分配到一個鏈表與字符數組節點
struct node
{
int id;
char name[20];
int sem;
struct node *link;
};
typedef struct node* Node;
Node getnode()
{
Node temp=(Node)(malloc(sizeof(Node)));
if(temp==NULL)
printf("\n Out of memory");
return temp;
}
Node ins_pos(Node first)
{
Node temp=getnode();
printf("\n Enter id ");
scanf("%d",&temp->id);
printf("\n Enter name ");
scanf("%s",temp->name);
printf("\n Enter semester ");
scanf("%d",&temp->sem);
if(first == NULL)
{
temp->link=NULL;
return temp;
}
else
{
int pos,i;
printf("\n Enter position: ");
scanf("%d",&pos);
if(pos == 1)
{
temp->link=first;
return temp;
}
else
{
Node prev=NULL,cur=first;
for(i=1; i<pos; i++)
{
if(cur==NULL)
break;
prev=cur;
cur=cur->link;
}
if(cur==NULL && i < pos)
printf("\n Position invalid");
else
{
prev->link=temp;
temp->link=cur;
}
return first;
}
}
}
Node del(Node first)
{
if(first==NULL)
printf("\n List is Empty ");
else
{
Node temp=first;
printf("\n ID: %d was deleted",temp->id);
first=first->link;
free(temp);
}
return first;
}
void disply(Node first)
{
if(first==NULL)
printf("\n List is empty");
else
{
Node cur=first;
while(cur!=NULL)
{
printf("\n ID : ");
printf("%d",cur->id);
printf("\n Name : ");
printf("%s",cur->name);
printf("\n Semester : ");
printf("%d",cur->sem);
printf("\n\n\n");
cur=cur->link;
}
}
}
int main()
{
Node first=NULL;
int opt;
do
{
printf("\n QUEUE MENU\n 1.Insert at position \n 2.delete front\n 3.display\n 4.Exit \n\n Enter your choice : ");
scanf("%d",&opt);
switch(opt)
{
case 1 :first = ins_pos(first);
break;
case 2 :first = del(first);
break;
case 3 :disply(first);
break;
}
}while(opt!=4);
return 0;
}
當插入一個新的節點簡單單鏈表程序,在malloc的聲明代碼塊崩潰。我怎麼知道?好吧,它在請求「輸入ID」之前崩潰。那麼,我做錯了什麼?
另一點是,它在節點中只有一個整數字段正常工作,這裏的問題可能是字符數組。
我注意到這個答案並不能解釋*爲什麼這解決了這個問題。 – immibis
@immibis我已經添加了解釋。如果您發現任何問題,請隨時指出。謝謝 !! :-) – ameyCU