Hmm I'm having trouble compiling a program from a book - I've tripled check to see if I got it right and I just can't see it. The compiler gives an error about 'void * being an unknown size'. The problem is in the is_sorted function.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int is_sorted(void *A, int nelem, int size, int (*cmp)(void *, void *));
int double_ascending(void *v1, void *v2)
{
double *d1 = v1;
double *d2 = v2;
if (d1 < d2)
return -1;
if (d1 > d2)
return 1;
return 0;
}
int string_descending(void *v1, void *v2)
{
char **s1 = v1;
char **s2 = v2;
return -strcmp(*s1,*s2);
}
int main(int argc, char **argv)
{
double X[] = {1.87, 3.43, 7.64};
char *S[] = {"wombat", "wallaby", "quoll", "quokka"};
if (is_sorted(X, sizeof(X)/sizeof(*X), sizeof(*X), double_ascending))
{
printf("Array X is ascending\n");
} else { printf("Array X is descending\n"); }
if (is_sorted( S, sizeof(S)/sizeof(*S), sizeof(*S), string_descending))
{
printf("Array S is descending\n");
} else { printf("Array S is ascending\n"); }
return 0;
}
int is_sorted(void *A, int nelem, int size, int (*cmp)(void *, void *))
{
while (nelem > 1)
{
if (cmp(A, A+size) > 0) { // <-- PROBLEM HERE
return 0; // out of order
}
A += size; // <-- PROBLEM HERE
nelem -= 1;
}
// all elements have been checked
return 1;
}
I'm not exactly sure why its generating an error as it makes sense to me (unfortunately not to the comp) but any suggestions on what is wrong would definitely be helpful! Thanks!