我目前正在学习单行列表,我正在尝试编写基本功能,并且在初始化了几个元素后尝试打印我的列表,但我的程序有一个逻辑包,因为我没有遇到编译错误,但它只返回一个非零值。我不知道错误/总线在哪里。可能它与打印功能有关,但我不确定
#include<stdio.h>
#include<stdlib.h>
typedef struct person{
int age;
struct person*next_generation;
}person;
struct person*head=NULL;
void insert_start(int tage){
struct person*next_gen=(person*) malloc(sizeof(person));
next_gen->age=tage;
next_gen->next_generation=head;
head=next_gen;
}
void insert_end(int x){
person*next_gen=(person*) malloc(sizeof(person));
next_gen->age=x;
next_gen->next_generation=NULL;
if(head==NULL)
head=next_gen;
else{
struct person*find=head;
while(find!=NULL){
find=find->next_generation;
}
find->next_generation=next_gen;
}
}
void insert_whenever(int x,person*p,int position){
person*next_gen=(person*)malloc(sizeof(person));
next_gen->age=x;
next_gen->next_generation=NULL;
int i=1;
while(i<position){
p=p->next_generation;
i++;
}
next_gen->next_generation=p;
p->next_generation=next_gen;
}
void print_list(person *p){
printf("[");
while(p!=NULL){
printf("%d",p->age);
p=p->next_generation;
}
printf("]");
}
int main(){
insert_start(75);
insert_end(45);
insert_end(12);
insert_whenever(32,head,3);
print_list(head);
return 0;
}
函数
insert_end
中的以下代码有一个错误:
while(find!=NULL){
find=find->next_generation;
}
find->next_generation=next_gen;
while
循环完成后,find
将具有值NULL
。在循环后的第一行中,取消引用 find
。不允许取消引用 NULL
指针,并且会调用未定义的行为。