I am writing code to read and write a text file. But when I run my code, I’m getting a SIGSEGV run-time error. I need help figuring out what is wrong with the code.
#include <stdio.h>
#include <stdlib.h>
int main(){
/*Variable for writing to file */
char *name[] = {"Raju", "Nayan", "Hanif"};
char *id[] = {"100", "101", "102"};
float cgpa[] = {3.50, 5.00, 4.00};
/*Variable for reading from file*/
char *getname, *getid;
float getcgpa;
int i;
FILE *fp;
fp = fopen("f:\\raju.nog", "w"); /*Create new file */
for(i=0; i<5; i++){
fprintf(fp, "%-10s%-10s%-1.2f\n", name[i], id[i], cgpa[i]); /*write to file*/
}
fclose(fp);
/*read from file and print to screen*/
fp = fopen("f:\\raju.nog", "r");
while(fscanf(fp, "%s %s %f", &getname, &getid, &getcgpa) != EOF){
printf("%-10s%-10s%-1.2f\n", getname, getid, getcgpa);
}
system("PAUSE");
}
The arrays:
declare 3 elements but
is trying to iterate over 5, thus overrunning the bounds of the arrays.