【问题标题】:Segmentation Fault from Scanf IntScanf Int 的分段错误
【发布时间】:2015-02-10 21:18:59
【问题描述】:

我不知道为什么会出现分段错误。我在网上看到的所有其他实例都有分段错误,因为 scanf 中的变量是一个指针。我的不是,我仍然得到错误

#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;
}

【问题讨论】:

  • 你得到 seg 错误,因为你没有在语句 current->grade=input 之前为结构分配内存,你应该分配内存 malloc head=malloc(sizeof(struct Node));

标签: c scanf


【解决方案1】:

是这一行,不是scanf

current->grade = input;

因为你没有为头部分配内存

【讨论】:

  • 哦,好的。这是用malloc完成的吗?类似于我创建 new_node 的方式?
  • struct Node *head =(struct Node *) malloc(sizeof(struct Node));
  • 好的,谢谢,我不必对 current 执行此操作,因为我只是设置等于 head?另外 (struct Node *) 的目的是什么?
  • @MikeOles 你不需要在 C 中显式转换 (struct Node *),因为 malloc 返回 void *,它只是一个优先问题
  • @Mike Oles,更简单:struct Node *head = malloc(sizeof *head);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 1970-01-01
  • 2020-12-15
相关资源
最近更新 更多