scanfint的分段错误
我不知道为什么会出现分割错误。我在网上看到的每个其他实例都有分段错误,因为scanf中的变量是指针。我的不是,我仍然得到错误scanfint的分段错误,c,scanf,C,Scanf,我不知道为什么会出现分割错误。我在网上看到的每个其他实例都有分段错误,因为scanf中的变量是指针。我的不是,我仍然得到错误 #include<stdio.h> #include<stdlib.h> struct Node { int grade; struct Node *next; }; int main() { int input; struct Node *head, *current;
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int grade;
struct Node *next;
};
int main()
{
int input;
struct Node *head, *current;
current = head;
printf("Enter Grades: \n");
do
{
scanf("%d",&input);
current->grade = input;
struct Node *new_node = malloc(sizeof(struct Node));
current->next = new_node;
current = current->next;
}while(input != -1);
return 0;
current = head;
}
#包括
#包括
结构体类型
{
国际等级;
结构节点*下一步;
};
int main()
{
int输入;
结构节点*头,*当前;
电流=水头;
printf(“输入等级:\n”);
做
{
scanf(“%d”,输入(&I));
当前->等级=输入;
结构节点*新节点=malloc(sizeof(结构节点));
当前->下一步=新节点;
当前=当前->下一步;
}while(输入!=-1);
返回0;
电流=水头;
}
是这一行,不是scanf
current->grade = input;
因为您没有为头部分配内存哦,好的。malloc就这样了吗?类似于我创建新_节点的方式?struct node*head=(struct node*)malloc(sizeof(struct node));好的,谢谢你们,我不需要用电流来做这个,因为我只需要设置为等于头部?(struct Node*)的目的是什么?@MikeOles在C中不需要显式强制转换(struct Node*),因为malloc返回void*,这只是一个简单的问题prefrence@MikeOles,更简单:
struct Node*head=malloc(sizeof*head)代码>由于在语句current->grade=input之前没有为结构分配内存,所以得到seg fault,应该使用malloc head=malloc(sizeof(struct Node))分配内存;