linux gcc 无头链表 段错误
#ifndef LIST_H__#define LIST_H__ //声明部分 .h
#define NAMESIZE 32
struct student
{
char name[NAMESIZE];
int num;
int math;
int chinese;
};
struct list //建立链表头节点
{
struct student data;
struct list *next;
};
int zhengjia(struct list **,struct student *data);
int show(struct list *);
int chaxun(struct list *,int num);
#endif
#include <stdio.h> // 声明.c文件部分
#include <stdlib.h>
#include "list.h"
int zhengjia(struct list **pre,struct student *data)
{
struct list *new;
if(new == NULL)
return -1;
new = malloc(sizeof(*new));
new -> next = *pre;
new -> data = *data;
*pre = new;
return 0;
}
int show(struct list *pre)
{
struct list *head;
for(head = pre; head != NULL;head = head -> next)
{
printf("%s %d %d %d\n",head -> data.name,head -> data.num,head -> data.math,head -> data.chinese);
}
}
int chaxun(struct list *pre,int num)
{
struct list *head;
for(head = pre;head != NULL;head = head -> next)
{
if(head -> data.num == num)
printf("%s %d %d %d\n",head -> data.name,head -> data.num,head -> data.math,head -> data.chinese);
return 0;
}
return -1;
}
void shifang(struct list *pre)
{
struct list *head;
for(head = pre;head != NULL;head = pre)
{
pre = head -> next;
free(head);
}
}
#include <stdio.h>
#include <stdlib.h> //main.c部分,只能执行到show部分,
//chaxun(),有错
#include "list.h" //返回整形,不执行,也不报错
int main() //返回struct student *类型,就报段错误
{
struct list *pre = NULL;
struct student tmp,*js;
int i,ret,num = 2;
for(i = 0;i < 7 ;i++)
{
snprintf(tmp.name,NAMESIZE,"stu%d",i);
tmp.num = i;
tmp.math = rand() % 100;
tmp.chinese = rand() % 100;
ret = zhengjia(&pre,&tmp);
if(ret !=0)
exit(1);
}
show(pre);
printf("\n\n");
chaxun(pre,num);
shifang(pre);
exit(0);
}