Problem: The following code:
int *readGrades() {
int *grades;
int x;
scanf("%d", &x);
grades = malloc(x * sizeof(int));
return 0;
}
reads 1 int
from the standard input, THEN it allocates an array of int
s and it return
s 0
which zero-initializes caller's pointer when used like this:
int* grades = readGrades();
Solution: Apart from reading the count of grades, the function should read the grades as well. The array should be initialized BEFORE the reading and the actual reading of grades should be done in a loop, which would initialize array's elements. At the end, a pointer to the first element should be returned:
int *readGrades(int count) {
int *grades = malloc(count * sizeof(int));
for (i = 0; i < count; ++i) {
scanf("%d", &grades[i]);
}
return grades; // <-- equivalent to return &grades[0];
}
...
int count;
scanf("%d", &count); // <-- so that caller knows the count of grades
int *grades = readGrades(count);