|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
为什么这个在储存第二个人的数据时会报错啊??
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- #define LEN sizeof(struct cesh)
- struct cesh* creat();
- void print(struct cesh*head);
- int i;
- void main()
- {
- struct cesh* stu;
- stu = creat();
- print(stu);
- system("pause");
- }
- struct cesh
- {
- int xuehao;
- double score;
- struct cesh* next;
- };
- struct cesh* creat()
- {
- struct cesh *p1,*p2,*head;
- p1 = p2 = (struct cesh*)malloc(LEN);
- printf("输入学号。\n");
- scanf_s("%d", &p1->xuehao);
- printf("输入成绩。\n");
- scanf_s("%lf", &p1->score);
- head = NULL;
- i = 0;
- while (p1->xuehao)
- {
- i++;
- if (i == 1)
- {
- head = p1;
- }
- else
- {
- p2->next = p1;
- }
- p2 = p1;
- p1 = (struct cesh*)malloc(LEN);
- printf("输入学号\n");
- scanf_s("%d",p1->xuehao);
- printf("输入成绩\n");
- scanf_s("%lf",p1->score);
- }
- p2->next = NULL;
- return head;
- }
- void print(struct cesh* head)
- {
- struct cesh* p;
- printf("\n这里一共有 %d 个数据\n\n", i);
- p = head;
- if (head)
- {
- do
- {
- printf("学号为 %d 的成绩为 %0.2f.\n", p->xuehao, p->score);
- p = p->next;
- } while (p);
- }
- }
复制代码
问题出在以下这行代码:
- scanf_s(\%d\, p1->xuehao);
复制代码
以及
- scanf_s(\%lf\, p1->score);
复制代码
在这里,你应该传递变量的地址给 scanf_s函数,而不是变量的值。所以需要修改为:
- scanf_s(\%d\, &(p1->xuehao));
复制代码
以及
- scanf_s(\%lf\, &(p1->score));
复制代码
修改后的完整代码如下所示:
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- #define LEN sizeof(struct cesh)
- struct cesh* creat();
- void print(struct cesh* head);
- int i;
- int main() {
- struct cesh* stu;
- stu = creat();
- print(stu);
- system(\pause\);
- return 0;
- }
- struct cesh {
- int xuehao;
- double score;
- struct cesh* next;
- };
- struct cesh* creat() {
- struct cesh* p1, * p2, * head;
- p1 = p2 = (struct cesh*)malloc(LEN);
- printf(\输入学号。\
- \);
- scanf_s(\%d\, &(p1->xuehao));
- printf(\输入成绩。\
- \);
- scanf_s(\%lf\, &(p1->score));
- head = NULL;
- i = 0;
- while (p1->xuehao) {
- i++;
- if (i == 1) {
- head = p1;
- }
- else {
- p2->next = p1;
- }
- p2 = p1;
- p1 = (struct cesh*)malloc(LEN);
- printf(\输入学号\
- \);
- scanf_s(\%d\, &(p1->xuehao));
- printf(\输入成绩\
- \);
- scanf_s(\%lf\, &(p1->score));
- }
- p2->next = NULL;
- return head;
- }
- void print(struct cesh* head) {
- struct cesh* p;
- printf(\\
- 这里一共有 %d 个数据\
- \
- \, i);
- p = head;
- if (head) {
- do {
- printf(\学号为 %d 的成绩为 %0.2f.\
- \, p->xuehao, p->score);
- p = p->next;
- } while (p);
- }
- }
复制代码
这样修改后,你应该能够正确地储存第二个人的数据了。
|
|