malloc内存分配失败
#include <stdio.h>#include <string.h>
struct book //书籍信息的结构
{
int book_id;
char book_name; //一个书的id、一个书名、5个关键字、3个作者、一个发布地、一个发布时间
char keyword1;
char keyword2;
char keyword3;
char keyword4;
char keyword5;
char author1;
char author2;
char author3;
char publisher;
char publish_time;
struct book *next;
}*Book;
struct book *data_book_input();
void main()
{
struct book *head;
head = data_book_input();
printf("%d\n",head->book_id);
head = head->next;
printf("%d",head->book_id);
}
struct book *data_book_input()
{
struct book *p,*head,*tail;
head = tail = NULL;
int book_id;
char book_name;
char keyword1;
char keyword2;
char keyword3;
char keyword4;
char keyword5;
char author1;
char author2;
char author3;
char publisher;
char publish_time;
FILE *f = NULL;
if((f=fopen("data.txt","r")) == NULL)
{
printf("File is Error! No1\n");
return NULL;
}
while(fscanf(f, "%d %s %s %s %s %s %s %s %s %s %s %s",
&book_id,book_name,keyword1,keyword2,keyword3,keyword4,keyword5,
author1,author2,author3,publisher,publish_time) != EOF)
{
if((p = (struct book *)malloc(sizeof(struct book)))==NULL); //分配储存空间
{
printf("Error!");
return NULL;
}
p->book_id = book_id; //导入数据
strcpy(p->book_name , book_name);
strcpy(p->keyword1 , keyword1);
strcpy(p->keyword2 , keyword2);
strcpy(p->keyword3 , keyword3);
strcpy(p->keyword4 , keyword4);
strcpy(p->keyword5 , keyword5);
strcpy(p->author1 , author1);
strcpy(p->author2 , author2);
strcpy(p->author3 , author3);
strcpy(p->publisher , publisher);
strcpy(p->publish_time , publish_time);
p->next = NULL; //顺序建立链表
if(head == NULL)
head = p;
else
tail->next = p;
tail = p;
} //链表头地址是head,最后的next是NULL
fclose(f);
return head;
}
为什么运行后出来的是 Error!,求指正,谢谢 两个地方:
1. 使用malloc要引入头文件 #include <stdlib.h>
2. if((p = (struct book *)malloc(sizeof(struct book)))==NULL);==>> 这里多了个分号
页:
[1]