【发布时间】:2015-11-11 22:53:51
【问题描述】:
一点帮助? 我很确定答案一定很愚蠢,但我不明白为什么我在 scanf 之后立即出现分段错误。我已经盯着我的一段代码很久了:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Student{
int grade, id;
struct Student *next;
}student;
student *initialize(){
return NULL;
}
int main(){
student *init;
student *nxt;
student *actual;
int resp;
init = (student*)malloc(sizeof(student));
init = initialize();
actual = init;
while(1){
printf("type grade:\n");
scanf("%d", &actual->grade);
printf("type id:\n");
scanf("%d", &actual->id);
printf("wanna continue? (1-YES e <other>-NO)\n");
if(resp==1){
actual->next=(student*)malloc(sizeof(student));
nxt=actual->next;
}else
break;
}
actual->next=NULL;
return 0;
}
没什么大不了的,对吧?有一个结构,我想将一个值扫描到其中。在我的终端上,我得到:
type grade:
3
Segmentation fault (core dumped)
有什么想法吗?
【问题讨论】:
-
改用
scanf("%s", actual.grade) -
你在调用initialize时将init的值设置为NULL。
-
为什么初始化后设置init为null,返回NULL...
-
这里还有一个bug,使用scanf和回车...
-
尝试使用 for() 循环,而不是 while()。它简化了生活!
标签: c pointers memory segmentation-fault