要求用链表加结构体完成如下简易的图书管理程序,运行时出现报错如下图,想请教一下应该怎么改。
问题描述:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct info
{
int num;
char name[20];
char author[20];
int price;
};
typedef struct node
{
info book;
struct node* next;
}node;
void initiatesl(node* h)
{
h = (node*)malloc(sizeof(node));
h->next = NULL;
}
void add(node* h, info* p)
{
node* q, * t;
q = (node*)malloc(sizeof(node));
t = (node*)malloc(sizeof(node));
q->book.num = p->num;
strcpy(q->book.name, p->name);
strcpy(q->book.author, p->author);
q->book.price = p->price;
if (h->next == NULL)
h->next = q;
else t->next = q;
t = q;
t->next = NULL;
}
void delete_(node* h, int i)
{
node* p, * s;
int j;
p = h;
j = 0;
while (p->next != NULL && j < i - 1)
{
p = p->next;
j++;
}
if (j != i - 1 || p->next == NULL)
{
printf("i is invalid \n");
exit(0);
}
s = p->next;
p->next = s->next;
free(s);
}
void print(node* h);
void sort(node* h)
{
node* x;
node* h1;
h1= (node*)malloc(sizeof(node));
initiatesl(h1);
while (h->next != NULL) {
x = h->next;
int i = 0, minnum = 1;
int min = 0;
min = x->book.price;
node* p, * t;
p = (node*)malloc(sizeof(node));
t = (node*)malloc(sizeof(node));
while (x != NULL) {
if (x->book.price < min) {
minnum = i + 1;
min = x->book.price;
p = x;
}
i++;
x = x->next;
}
if (h1->next == NULL)
h1->next = p;
else t->next = p;
t = p;
delete_(h, minnum);
}
print(h1);
}
void print(node* h)
{
printf("编号\t书名\t作者\t价钱\n");
node* x;
x = (node*)malloc(sizeof(node));
x = h->next;
while (x != NULL) {
printf("%d\t%s\t%s\t%d\n", x->book.num, x->book.name, x->book.author, x->book.price);
x = x->next;
}
}
int main()
{
node* h;
h = (node*)malloc(sizeof(node));
initiatesl(h);
info data[4];
data[0] = { 100001,"Basic","zhang",15 };
data[1] = { 200022,"VB","Li",20 };
data[2] = { 383283,"C","Wang",18 };
data[3] = { 324444,"delphi","Zhao",23 };
for (int i = 0; i < 4; i++) {
add(h, &data[i]);
}
print(h);
printf("删除第二个\n");
delete_(h, 2);
print(h);
printf("排序完成后\n");
sort(h);
return 0;
}
答
初始化方法是错的。既然111行已经给头指针申请了空间,那么初始化函数里就直接用,不要再申请一次了。第21行删除掉
第100行也是没有意义的代码,删除掉