I'm trying to a function that takes as arguments an array (in this case it's void since the goal is to make it "compatible" with any numerical types), its size and the function that it wants to evaluate. Everything seemed to be working fine, since it compiled with no errors, but it returned (printed) weird values.
Sure enough, after priting in each function, the pointer was pointing to some weird numbers in my memory and not actually the array I passed to the countSelect function (and then the minor functions).
I'm new to pointers and playing with C at this level, and would massively appreciate someone more experienced telling me what's actually wrong (and suggestions for improving it/avoiding it).
#include <stdio.h>
int selNegInt(void * num) {
int * pointToNum = (int *) num;
//printf("1 - %d\n", *pointToNum);
return *pointToNum < 0; //or *((int *) num)
}
int selEvenInt(void * num) {
int * pointToNum = (int *) num;
//printf("2 - %d\n", *pointToNum);
return *pointToNum % 2 == 0;
}
int selOddIn(void * num) {
int * pointToNum = (int *) num;
//printf("3 - %d\n", *pointToNum);
return *pointToNum % 2 != 0;
}
int selGt10In(void * num) {
int * pointToNum = (int *) num;
//printf("4 - %d\n", *pointToNum);
return *pointToNum > 10;
}
int countSelected(void * a , int size, int sizelem, int (*select)(void *)) {
int total=0;
for (int i=0; i<size/sizelem; i++) {
if (select(a+i)) total++;
}
return total;
}
int main(void) {
int a[] = {-1, 24, 0, 2141, -241, 2415};
printf("Num negs = %d\n", countSelected(a, sizeof(a), sizeof(*a), selNegInt));
printf("Num evens = %d\n", countSelected(a, sizeof(a), sizeof(*a), selEvenInt));
printf("Num odds = %d\n", countSelected(a, sizeof(a), sizeof(*a), selOddIn));
printf("Num greater than 10 = %d\n", countSelected(a, sizeof(a), sizeof(*a), selGt10In));
return 0;
}