struct film { char title[TSIZE]; int rating; struct film * next; /* points to next struct in list */ };
int main(void) { struct film * head = NULL; struct film * prev, * current; char input[TSIZE];
/* Gather and store information */ puts("Enter first movie title:"); while (gets(input) != NULL && input[0] != '\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) { free(current); current = current->next; } printf("Bye!\n");
我看的是《c primer plus》第5版的489面,我在visual studio c++2008 下运行后没出现错误,但是在运行窗口过后会出现一个“遇到问题需要关闭,我们对此感到。。。”的窗口提示,但是在MinGW Developer studio下运行就正常,我个人也是认为应该建立一个临时的指针来保存current->next值