C Primer Plus(第六版)中文版 中的錯誤1。本站提示廣大學習愛好者:(C Primer Plus(第六版)中文版 中的錯誤1)文章只能為提供參考,不一定能成為您想要的結果。以下是C Primer Plus(第六版)中文版 中的錯誤1正文
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4 #define TSIZE 45
5
6 struct film {
7 char title[TSIZE];
8 int rating;
9 struct film *next;
10 };
11 char * s_gets(char * st, int n);
12
13 int main(void)
14 {
15 struct film * head = NULL;
16 struct film * prev;
17 struct film * current;
18 char input[TSIZE];
19
20 puts("Enter first movie title:");
21 while(s_gets(input, TSIZE) != NULL && input[0] != '\0')
22 {
23 current = (struct film *) malloc(sizeof(struct film));
24 if(head == NULL)
25 head = current;
26 else
27 prev->next = current;
28 current->next = NULL;
29 strcpy(current->title, input);
30 puts("Enter your rating <0-10>:");
31 scanf("%d", ¤t->rating);
32 while(getchar() != '\n')
33 continue;
34 puts("Enter next movie title (empty line to stop):");
35 prev = current;
36 }
37
38 if(head == NULL)
39 printf("No data entered. ");
40 else
41 printf("Here is the movie list:\n");
42 current = head;
43 while(current != NULL)
44 {
45 printf("Movie: %s Rating: %d\n",
46 current->title, current->rating);
47 current = current->next;
48 }
49
50 current = head;
51 while(current != NULL)
52 {
53 current = head;
54 head = current->next;
55 free(current);
56 }
57 printf("Bye!\n");
58
59 return 0;
60 }
61
62 char * s_gets(char * st, int n)
63 {
64 char * ret_val;
65 char * find;
66
67 ret_val = fgets(st, n, stdin);
68 if(ret_val)
69 {
70 find = strchr(st, '\n');
71 if(find)
72 *find = '\0';
73 else
74 while(getchar() != '\n')
75 continue;
76 }
77
78 return ret_val;
79 }
View Code
下面的代碼來自《C Primer Plus》(第六版)中文版,第573-574頁。
其中代碼的第51行有錯誤。
不知道這個錯誤是印刷有錯,還是原書有錯。在此指出。
矯正代碼:
是將第51行的while(current != NULL)改為
while (head != NULL)就可以了。
緣由如下:
將第51-56行代碼之間添加一些輸入,代碼如下:
1 while(current != NULL)
2 {
3 printf("current1 = %p\n", current);
4 printf("head1 = %p\n\n",head);
5 current = head;
6 printf("current2 = %p\n", current);
7 printf("head2 = %p\n\n",head);
8 head = current->next;
9 printf("current3 = %p\n", current);
10 printf("head3 = %p\n\n",head);
11 free(current);
12 printf("current4 = %p\n", current);
13 printf("head4 = %p\n\n",head);
14 }
View Code
輸入後果如下:
從下面的輸入後果可以看出,最後一個head2指針曾經是00000000了,是一個指向未知地址的指針。所以再次釋放一個current就會出錯。
矯正後的輸入: