[英]Why does my program crashes when I tried adding a node inside a function but works in the main function
我嘗試使用以下方法為鏈表分配新節點:
struct node *n;
n=(struct node*)malloc(sizeof(struct node));
當我嘗試在我稱為newnode()
的函數中執行此操作時,它崩潰了。 但是,當它在main()
函數內部完成時,我的完整代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct node{
int item;
struct node *next;
};
struct linkedlist{
int size;
struct node *head;
};
void split(struct linkedlist *LL,struct linkedlist *L_odd,
struct linkedlist *L_even);
void printlist(struct linkedlist *LL);
void generate();
void newnode(int i,struct linkedlist *LL);
int main(){
struct linkedlist *L=(struct linkedlist*)malloc(sizeof(struct linkedlist));
L->head->item=1;
newnode(2,L);
newnode(3,L);
printlist(L);
return 0;
}
void split(struct linkedlist *LL,struct linkedlist *L_odd,
struct linkedlist *L_even){
bool odd=1;
bool start=1;
struct node *temp=malloc(sizeof(struct node));
struct node *tempo=L_odd->head;
struct node *tempe=L_even->head;
temp=LL->head;
while (temp->next != NULL){
if(odd==1){
if (start == 1 ){
start=0;
}
else{
tempe->next=temp->next;
tempe=tempo->next;
}
tempo->item=temp->item;
odd=0;
}
else if(odd==0){
tempo->next=temp->next;
tempo=tempo->next;
L_even->head->item=temp->item;
odd=1;
}
temp=temp->next;
}
}
void printlist(struct linkedlist *LL){
struct node *temp=LL->head;
do{
printf("%d ",temp->item);
temp=temp->next;
}while(temp!= NULL);
}
void generate(){
}
void newnode(int i,struct linkedlist *LL){
struct node *n;
n=(struct node*)malloc(sizeof(struct node)); //Program crashes here
printf("%d",LL->head->item);
//n->item=i;
struct node *temp=LL->head;
while (temp->next!=NULL){
temp=temp->next;
}
//temp->next=n;
//n->next=NULL;
}
為什么會這樣呢?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.