It's mainly used in function prototypes to indicate a pointer whose type is only known at runtime.
So, one could write a trivial function to sort an array of ints:
#include
#include
int cmp_int(const void *a, const void *b);
int main(void)
{
int a[] = { 1, 5, 2, 9, 3};
size_t n = sizeof a / sizeof a[0];
qsort(&a, n, sizeof a[0], cmp_int);
for (i=0; i < n; i++)
printf("%d\n", a[i]);
return EXIT_SUCCESS;
}
int cmp_int(const void *a, const void *b)
{
const int *f = a;
const int *s = b;
/* Here, one cannot perform *a < *b */
if (*f < *s) {
return -1;
} else if (*f > *s) {
return 1;
} else {
return 0;
}
}
No comments:
Post a Comment