c - 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]);
}
}
解决方案
您的代码中有多个问题:
- 原型
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]);
}
}
推荐阅读
- r - lapply / purrr::map 之类的函数默认允许访问索引?
- laravel - Laravel 5.4 在专用日志文件中记录 404
- wix - 覆盖 CustomActionData WIX 中的值
- php - ajax成功数组括号属性不返回内容
- amazon-s3 - 如何在启动期间阻止我的应用程序填充 S3 暂存目录?
- pdf - poppler pdfunite 无法合并加密的 PDF 文件,如何解除加密?(无需密码即可打开)
- c# - 无法将 json 反序列化为 C# 对象
- python-3.x - 语法错误;名称“x”是参数且非本地
- c++ - 用于注册事件处理程序的模板函数
- java - Android:java.lang.IllegalArgumentException:输入张量索引无效:1