The problems lies with this statement:
pass[i] = scores[i];
You don't want to copy the score into the element with the same index; you want to copy it into the first "free" slot. You'll need to keep track of how elements of pass
are being used.
There's a second problem: You output size
numbers, even if there are fewer passing grades.
In this case, rather than having to communicate the number of elements in the returned array to the caller, we could simply place a 0
at the end to indicate the end. But we have to be careful of the case where all the grades are passing grades!
A minor third problem: You are considering a grade of 36 to be a failing grade! Let this be a lesson in testing: Whenever you do testing, always test at and around the limits (so you'd test with scores of 35, 36 and 37 in this case).
Finally, you dynamically allocate an array, but you never free it. It's not critical that you free it because you'd do so just before exiting the program, but that's a bad habit to get into. (One possible consequence is that it would cause the output of tools such as valgrind
to become very noisy if you decide to use it to help resolve a crash.)
#include <stdio.h>
#include <stdlib.h>
int* getPassingScores(const int* scores, int num_scores) {
const int passingScore = 36;
// calloc is like malloc, but the memory will
// be efficiently initialized to 0. This means
// we don't need to do pass[j] = -1; later.
// Need to make sure we have enough space
// when all the grades are passing grades!
int* pass = calloc(num_scores, sizeof(int));
if (!pass)
return NULL;
for (int i=0, j=0; i<num_scores; ++i) {
if (scores[i] >= passingScore) {
pass[j++] = scores[i];
}
}
return pass;
}
int main(void) {
int scores[] = {55, 35, 60, 25, 10, 43};
int num_scores = sizeof(scores)/sizeof(*scores);
int* passingScores = getPassingScores(scores, num_scores);
for (int i=0; passingScores[i]>0; ++i) {
printf("%d\n", passingScores[i]);
}
free(passingScores);
return 0;
}
Of course, the following would suffice:
#include <stdio.h>
int main(void) {
int scores[] = {55, 35, 60, 25, 10, 43};
int num_scores = sizeof(scores)/sizeof(*scores);
const int passingScore = 36;
for (int i=0; i<num_scores; ++i)
if (scores[i] >= passingScore)
printf("%d\n", scores[i]);
}