《C Primer Plus(第六版)中文版》实践中发现的错误
一.1.书-17.2从数组到链表
用链表而不是数组来储存电影信息
书中的源代码
#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, * current;
char input[TSIZE];
puts("Enter first movie title:");
while (s_gets(input, TSIZE) != NULL && input[0] != '\0')
{
current = (struct film*)malloc(sizeof(struct film));
if (head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
strcpy_s(current->title,input);
puts("Enter your rating <0-10>:");
scanf_s("%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)
{
free(current);
head = current->next;
}
printf("Bye!\n");
return 0;
}
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;
}
2.实践
发现第一个细节错误,prev未进行初始化;
修改之后再来!
struct film* prev=NULL, * current;
给prev一个空指针常量
再来一次
发现
Bye!也没有输出
发现是释放已分配的内存时出错了
经过修改
while (current != NULL)
{
head = current->next;
free(current);
current = head;
}
3.再次实践
经过修改后 程序能正常运行!
4.完善后的源代码
#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=NULL, * current;
char input[TSIZE];
puts("Enter first movie title:");
while (s_gets(input, TSIZE) != NULL && input[0] != '\0')
{
current = (struct film*)malloc(sizeof(struct film));
if (head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
strcpy_s(current->title,input);
puts("Enter your rating <0-10>:");
scanf_s("%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)
{
head = current->next;
free(current);
current = head;
}
printf("Bye!\n");
return 0;
}
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;
}