gpt4 book ai didi

c - 您的程序中出现了访问冲突(段错误)

转载 作者:太空宇宙 更新时间:2023-11-04 01:23:08 24 4
gpt4 key购买 nike

有多少学生:2(效果很好)有多少学生:4(它给出错误“您的程序中出现了访问冲突(段错误)。”

为什么它会发生在我身上,我花了 4 个小时但无法弄清楚。

#include <stdio.h>


struct student
{
int rollno;
char name[20];
};

int main()
{
int n,i,j;

struct student detail[n];

printf("how many students: ");
scanf("%d",&n);
fflush(stdin);

for(i=0; i<n; i++)
{
printf("enter student no.%d\n",(i));
printf("Name: ");
gets(detail[i].name);
printf("Roll No: ");
scanf("%d",&detail[i].rollno);
fflush(stdin);
}

for(i=0; i<n; i++)
{
printf("Student no. %d Detail\n",(i+1));
printf("Name:\t\t%s \nRoll No: \t%d\n",detail[i].name,detail[i].rollno);
}

getch();
}

最佳答案

在您的代码中,主要问题是

 int n,i,j;
struct student detail[n];

您正在使用未初始化的 n。它调用 undefined behavior .您需要移动 detail[n]; 的定义您扫描了用户的值之后。

也就是说,

  1. 检查 scanf() 的返回值以确保成功。
  2. gets() 很危险,因为它会导致缓冲区溢出。请改用 fgets()
  3. 根据标准,fflush(stdin) 是 UB,删除它。
  4. getch() 应该是 getchar(),如果只包含 stdio.h

关于c - 您的程序中出现了访问冲突(段错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36792511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com