fscanf fails on an int
This is my first post on cprogramming.com, so I apologize if this is in the wrong section or the answer is easily found elsewhere.
I'm working on a program that will read in student grades from a file and echo them back out to another file with an average semester grade and letter grade.
My problem is that when my code attempts to read in the second student's grades, the program fails for no apparent reason.
here is the code giving me the problem:
My program seems to run through the first for loop once without a problem, but on the second run through, my program fails when it reaches the fscanf function in the second for loop.
int n = 0, i = 0, a = 0, b = 0;
fscanf(read, "%d,%d\n", max_numb_students, numb_grades);
n = *max_numb_students;
i = *numb_grades;
*student_list = (struct student*) malloc(n*sizeof(struct student*));
student_list[n]->lastname = fget_string(read, 1);
student_list[n]->firstname = fget_string(read, 2);
printf("%s ", student_list[n]->firstname);
fscanf(read, "%d", &b);
student_list[n]->id = b;
printf("%d ", student_list[n]->id);
student_list[n]->grades = (int *) malloc(i*sizeof(int *));
fscanf(read, "%d ", &b);
student_list[n]->grades[a] = b;
printf("%d ", student_list[n]->grades[a]);
I would appreciate ANY help, as I'm a beginner.
Thanks in advance.
Lose the stars on max_num_students and num_grades, everywhere you have them ... where you are using these variables you need integers, not pointers.
Hard to say exactly without context, and some helper functions, but one thing I noticed is that you're mallocing only enough space for max_numb_students pointers to student structs, not student structs. Also, you shouldn't cast malloc. The safest way to allocate something is:
Dereference the place you're storing it and you'll always get the right type and allocation size. Since you're storing it in *student_list, you should do sizeof(**student_list):
t = malloc(n * sizeof(*t));
You have a similar problem with your grades list. Don't cast it, and do sizeof(*(student_list[n]->grades)).
*student_list = malloc(n * sizeof(**student_list));
This could easily cause problems when you scan into one of those spots. You're probably already off the end of the memory you (incorrectly) allocated.
Thanks for the replies!
Long story short, your replies started a chain reaction that let me realize what i did wrong.
And it made me make my code look better and less jumbled.