- 论坛徽章:
- 2
|
本帖最后由 shinwu_chen 于 2013-09-29 12:33 编辑
- #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 movie title: ");
- while (gets(input) != NULL && input[0] != '\0')
- {
- current = (struct film *) malloc(sizeof(struct film));
- printf("%p", current);
- 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);
- free(current);
- printf("%p\n", current);
- current = current->next;
- }
- printf("Bye!\n");
- return 0;
- }
复制代码 下面是我的结果
localhost:c Shinwu$ ./films2.out
Enter first movie title:
warning: this program uses gets(), which is unsafe.
1
0x7ffab9c03930Enter your rating <0-10>:
1
Enter next movie title (empty line to stop):
2
0x7ffab9c03970Enter your rating <0-10>:
2
Enter next movie title (empty line to stop):
3
0x7ffab9c039b0Enter your rating <0-10>:
3
Enter next movie title (empty line to stop):
Here is the movie list:
Movie: 1 Rating 1
0x7ffab9c03930
Movie: 2 Rating 2
0x7ffab9c03970
Movie: 3 Rating 3
0x7ffab9c039b0
Bye!
好像free(current)了以后,current指向的内存地址并没有变,对free一个结构指针应该咋理解呢 - -、
————————————————————————————————————————————————————
刚才网上查了查,应该是free释放了current指向的内存块,他本身的地址并没有变,可current->next为什么还能获取到呢? |
|