CPP书上489页的那个链表问题求解。
c语言吧
全部回复
仅看楼主
level 9
jxdz232601 楼主
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define TSIZE 45
struct film{
char title[TSIZE];
int rating;
struct film *next;
};
int main(void)
{
struct film *head =NULL;
struct film *prev,*current;
char input[TSIZE];
puts("enter first film:");
/*创建链表,并输入数据*/
while(gets(input)!=NULL&&input[0]!='\0')
{
current=(struct film *)malloc(sizeof(struct film));
if(head==NULL)head=current;
elseprev->next=current;
current->next=NULL;
strcpy(current->title,input);
puts("enter your rating<0-10>: ");
scanf("%d",¤t->rating);
while(getchar()!='\n') continue;
puts("enter next movie title (emput to stop):");
prev=current;
}
/*打印数据*/
if(head==NULL)printf("no data!\n");
elseprintf("here is the movie list:\n");
current=head;
while(current!=NULL)
{
printf("movie: %s rating: %d\n",current->title,current->rating);
current=current->next;
}
/*清除内存*/
current=head;
while(current!=NULL)
{
free(current);
current=current->next;
}
printf("Bye!\n");
return 0;
}
书上有程序,不过我还是手打一遍。。。。
2012年08月16日 09点08分 1
level 9
jxdz232601 楼主
enter first film:
renda
enter your rating<0-10>:
1
enter next movie title (emput to stop):
here is the movie list:movie: renda rating: 1
运行到这里,出来一个报错框,大意是dbgheap.c文件中的1044行有误,应该是和malloc有关。
看运行情况,应该是到free哪里出错的,错误是Expression:_CrtIsValid HeapPointer(pUserData),大概指指针用错或是内存出错。。。
我可这应该是CPP书上原文啊。。。
2012年08月16日 09点08分 2
level 9
jxdz232601 楼主
八成是free有问题,因为我把free注释掉就运行正常了,我实在看不出free有啥错啊,cpp书上也是这么写的。
2012年08月16日 09点08分 3
1