首页 > 解决方案 > C中的分段错误

问题描述

当我尝试在我的 VS 代码中运行以下 C 程序时,它显示已转储分段错误核心。我该如何解决?

#include <stdio.h>
#include <string.h>

void read(student);
void display(student);

struct student {
    int roll, result;
    char name[20], depart[20], sex;
    float percent, marks[5];          
};

void main() {        
    struct student s;
    read(s);  
}

void read(struct student std) {
    int c = 0, i;
    printf("enter the roll no:");
    scanf("%d", &std.roll);
    printf("enter the name:\n");
    scanf("%s", std.name);
    printf("enter Sex:\n");
    scanf(" %c", &std.sex);
    printf("Enter the department:\n");
    scanf("%s", std.depart);
    printf("enter the marks in 5 subjects:\n");
    for (i = 0; i < 5; i++) {
        scanf("%d", std.marks[i]);      
    } 
}

标签: c

解决方案


您的代码中有多个问题:

  • 原型void read(student);void display(student);引用未定义的类型student
  • 调用函数是有问题的,read因为它与 C 库中进行系统调用以读取文件的类似函数冲突。要么制作它,static要么更好地重命名它read_student
  • 您将student结构按值传递给read函数:read只会修改其参数,而不是main函数中的结构。read应该接收指向调用者范围内结构的指针。
  • main应定义为int main(void)
  • scanf()期望指向目标变量的指针。像 in 一样传递变量值scanf("%d", std.marks[i])肯定会导致未定义的行为很可能导致崩溃。

这是修改后的版本:

#include <stdio.h>
#include <string.h>

struct student {
    int roll, result;
    char name[20], depart[20], sex;
    float percent, marks[5];          
};

void read_student(struct student *);
void display_student(const struct student *);

int main() {        
    struct student s;
    read_student(&s);
    return 0;
}

void read_student(struct student *std) {
    int i;
    printf("enter the roll no: ");
    scanf("%d", &std->roll);
    printf("enter the name:\n");
    scanf("%19s", std->name);
    printf("enter Sex:\n");
    scanf(" %c", &std->sex);
    printf("Enter the department:\n");
    scanf("%19s", std->depart);
    printf("enter the marks in 5 subjects:\n");
    for (i = 0; i < 5; i++) {
        scanf("%d", &std->marks[i]);      
    } 
}

推荐阅读