【发布时间】:2019-10-04 17:45:25
【问题描述】:
enter code here这只是我的代码的一部分,但是在使用调试程序后,我能够缩小分段错误来自在 while 循环中访问 i 的范围。
这是输入数据:
30218294 Super Man 2.9
39324809 Spider Man 3.5
48201093 Papa Smurf 1.9
39482010 Mickey Mouse 3.2
49384832 Minnie Mouse 3.4
-1
我尝试在循环之前设置i = 0 并更改while 循环的条件。
#include <stdio.h>
#include <cstring>
#include <string.h>
#include <stdlib.h>
struct student{
char fname[100];
char lname[100];
int euid;
float gpa;
};
/* Reads the data from a file and stores it in the array of structs */
void readData(struct student *db, int *size)
{
const char* file_name = "input";
FILE *infile;
infile=fopen(file_name,"r");
int i=0, euid;
fscanf(infile,"%d",&euid);
while(euid > 0){
db[i].euid = euid; //**ERROR: Segmentation Fault**
fscanf(infile,"%s%s%f%d",db[i].fname,db[i].lname,&db[i].gpa,&euid);
i++;
}
fclose(infile);
*size = i;
}
int main(void)
{
int size;
struct student* db[100];
/* read info from file */
readData(*db,&size);
return 0;
}
程序收到信号SIGSEGV,分段错误。 func.c:17 处 readData (db=0xb7fe173d, size=0xbffff278) 中的 0x00400729 17 db[i].euid = euid;
【问题讨论】:
-
你没有初始化
i。int i不会将i的值设置为零。 -
还有 db 指向的空间吗?
-
是的,它是一个结构 student struct student{ char fname[100];字符 lname[100];诠释 euid;浮动gpa; };
-
我的猜测是
db要么没有初始化,要么不够大,要么为空。 -
我是否也将 euid 设置为一个值?如果是这样,是什么?
标签: c arrays segmentation-fault