#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define TSIZE 45 struct film {
char title[TSIZE];
int rating;
struct film *next;
};
char * s_gets(char * st, int n); int main(void)
{
struct film * head = NULL;
struct film * prev;
struct film * current;
char input[TSIZE]; puts("Enter first movie title:");
while(s_gets(input, TSIZE) != NULL && input[] != '\0')
{
current = (struct film *) malloc(sizeof(struct film));
if(head == NULL)
head = current;
else
prev->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 (empty line to stop):");
prev = current;
} if(head == NULL)
printf("No data entered. ");
else
printf("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)
{
current = head;
head = current->next;
free(current);
}
printf("Bye!\n"); return ;
} char * s_gets(char * st, int n)
{
char * ret_val;
char * find; ret_val = fgets(st, n, stdin);
if(ret_val)
{
find = strchr(st, '\n');
if(find)
*find = '\0';
else
while(getchar() != '\n')
continue;
} return ret_val;
}
上面的代码来自《C Primer Plus》(第六版)中文版,第573-574页。
其中代码的第51行有错误。
不知道这个错误是印刷有错,还是原书有错。在此指出。
改正代码:
是将第51行的while(current != NULL)改为
while (head != NULL)就可以了。
原因如下:
将第51-56行代码之间添加一些输出,代码如下:
while(current != NULL)
{
printf("current1 = %p\n", current);
printf("head1 = %p\n\n",head);
current = head;
printf("current2 = %p\n", current);
printf("head2 = %p\n\n",head);
head = current->next;
printf("current3 = %p\n", current);
printf("head3 = %p\n\n",head);
free(current);
printf("current4 = %p\n", current);
printf("head4 = %p\n\n",head);
}
输出结果如下:
从上面的输出结果可以看出,最后一个head2指针已经是00000000了,是一个指向未知地址的指针。所以再次释放一个current就会出错。
改正后的输出: