|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
下面是一个单向动态链表
- #include<stdio.h>
- #include<malloc.h>
- #define LEN sizeof(struct stu)
- struct stu
- {
- int num;//学生学号
- float score;//学生成绩
- struct stu *next;
- };
- int n=0;
- void main ()
- {
- struct stu *p1,*p2,*head;
- p1=malloc(LEN);
- printf("请输入学生学号:\n");
- scanf("%d",&p1->num);//这里用了取址符号
- printf("请输入学生成绩:\n");
- scanf("%f",&p1->score);
- head=p1;
- p2=p1;
- while(p1->num!=0)
- {
- n++;
- p1=malloc(LEN);
- printf("请输入学生学号:\n");
- scanf("%d",p1->num);//这里没用取址符号
- printf("请输入学生成绩:\n");
- scanf("%f",p1->score);
- if(p1->num)
- {
- p2->next=p1;
- p2=p1;
- }
- }
- p2->next=NULL;
- printf("数据录入完成\n");
- printf("\n\n");
- printf("你总共录入%d组数据!\n",n);
- p1=head;
- while(p1!=NULL)
- {
- printf("学号为%d的学生的成绩为%f:\n",p1->num,p1->score);
- p1=p1->next;
- }
- }
复制代码
如上面注释,在后面没用取址符号&,出现了这个错误
(这个使用code block运行时出现错误)
(这个是在linux运行时出现的错误)
可是给指针赋值的时候不是可以不加取址符号么?为什么还会出现错误,我把取址符号加上就没任何问题了,这是为什么?
scanf 需要知道将获取的数据保存到哪个变量中,所以需要用取址运算符(&)获得变量的地址。
在这道题里,p1 -> num 和 p1 -> score 都是结构体中的一个变量而非其地址,所以需要在其前面加上 &。p1 指向的是结构体的地址,p1 -> num 意思是通过 p1 指向的结构体地址来获取 num 成员的值。
|
|