[英]Segmentation Fault in C while loop to populate array
該文件是一個.bin 文件。 在終端調用function時,程序打開文件,出現分段錯誤。 我是否混淆了我的一種類型,或者可能沒有正確使用指針? 非常感謝您的幫助,感謝您查看
int main(int argc, char *argv[])
{
Student bank[20];
FILE * rfile;
Student *pStudent;
int i=0, n, end, count=0;
float graded;
char *stufile, name[256];
if (argc < 2)
{
stufile = (char *)malloc(MAX_NAME+1);
printf("What file would you like to open? ");
scanf("%s", stufile);
if (stufile ==NULL) return 1;
}
else{
stufile = argv[1];
}
// open file
rfile = fopen(stufile,"rb");
if (rfile == NULL){
printf("File not found\n");
return 1;
}
else{
printf("\n\n%-20s %-10s %10s\n","Name", "E-mail", "Grade");
printf("------------------------------------------\n");
fseek(rfile, 0, SEEK_END);
end = ftell(rfile); // will get to the EOF returning a int
fseek(rfile,0,SEEK_SET); // set cursor back
// I think this is seg fault??
while(fread(&bank[i++], sizeof(Student), 1, rfile) == 1){
if(feof(rfile)) break;
++count;
}
fclose(rfile);
}
for (i=0; i<count; ++i){
// print student info
printf("%-20s, %s %-10s %d%%\n", bank[i].lastName, bank[i].firstName,
bank[i].emailAddress, bank[i].grade);
n = n + bank[i].grade;
}
graded = n/count;
printf("Average Grade:\t\t%.2f", graded);
return 0;
}```
Good news no longer seg fault now it is printing off[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/rZKAW.png
因為您在&bank[i++]
中使用i
而不對其進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.