|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
RT,程序来自鱼哥的教学视频,按我的理解,链表在内存中就是一段数据,在这个程序中没有用到每个结构体的结构体名,而是用指针交叉地定义赋值,最后也是用的指针来读取的,我理解是指针就是一个地址数据,就是说可以靠对地址的读取来定义和读取链表?
另外,链表其实就是一种结构体?我的理解不错吧?
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- #define LEN sizeof(struct student) //student结构的大小
- struct student
- {
- int num;
- float score;
- struct student *next;
- };
- struct student *creatic(); //创建链表
- void print(struct student *head); //打印链表, 可以为 void print()
- int n;
- int main()
- {
- struct student *stu;
- stu = creatic();
- print(stu);
- printf("\n\n");
- system("pause");
- return 0;
- }
- struct student *creatic()
- {
- struct student *head;
- struct student *p1, *p2;
- p1 = p2 = (struct student *)malloc(LEN); //LEN是student结构的大小
- printf("Please enter the num: ");
- scanf("%d", &p1->num);
- printf("Please enter the score: ");
- scanf("%f", &p1->score);
- head = NULL;
- n = 0;
- while(p1->num) //即:while(p1-> num != 0)
- {
- n++;
- if(1 == n)
- {
- head = p1;
- }
- else
- {
- p2->next = p1;
- }
- p2 = p1;
- p1 = (struct student *)malloc(LEN);
- printf("\nPlease enter the num: ");
- scanf("%d", &p1->num);
- if(!p1->num)
- {
- break;
- }
- printf("Please enter the score: ");
- scanf("%f", &p1->score);
- }
- p2->next = NULL;
- return head;
- }
- void print(struct student *head)
- {
- struct student *p;
- printf("\nThere are %d records!\n\n", n);
- p = head;
- if(head) // NULL != head;
- {
- do
- {
- printf("The student whose number is %d score is :%f\n", p->num, p->score);
- p = p->next;
- }while(p); //NULL != p;
- }
- }
复制代码
你的理解没错。其实任何变量都是保存在内存中的,都可以通过地址来访问它。
对于有名字的变量,是编译器在管理它的生存周期,所以编译器可以将a,b,c这些变量名在编译时转换为对应的地址。
对于无名变量,就像你这里的链表malloc后,天晓得你什么时候free它,这时,编译器就不可能再管理它的生命周期,就要靠你来管理它的生命周期(就是说你应该在合适的时候free它)。所以编译器就没有必要给这类变量起名字。。。所以你一般就只能自己通过地址来访问它们。
|
|