strcmp强制类型转换后不能直接用于qsort, 需要进一步的包装……
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int (*cmp_func)(const void *, const void *);
int strcmp_for_qsort(const void *a, const void *b)
{
char *x = *(char **)a, *y = *(char **)b;
return strcmp(x, y);
}
void quicksort(void *p, int num, unsigned size, cmp_func cmp)
{
int i, j;
char *pos, *t = (char *) malloc(size);
if (t == NULL) exit(1);
for (i = 0; i < num; i++)
{
for (j = 0, pos = (char *)p; j < num - 1; j++, pos += size)
{
if (cmp(pos, pos + size) > 0)
{
memcpy(t, pos, size);
memcpy(pos, pos + size, size);
memcpy(pos + size, t, size);
}
}
}
free(t);
}
int main()
{
char *pos[5] = {"a", "c", "e", "b", "d"};
//qsort(pos, 5, sizeof(pos[0]), strcmp_for_qsort); // in stdlib
quicksort(pos, 5, sizeof(pos[0]), strcmp_for_qsort); //fake
for (int i = 0; i < 5; i++)
puts(pos[i]);
return 0;
}
#include <stdlib.h>
#include <string.h>
typedef int (*cmp_func)(const void *, const void *);
int strcmp_for_qsort(const void *a, const void *b)
{
char *x = *(char **)a, *y = *(char **)b;
return strcmp(x, y);
}
void quicksort(void *p, int num, unsigned size, cmp_func cmp)
{
int i, j;
char *pos, *t = (char *) malloc(size);
if (t == NULL) exit(1);
for (i = 0; i < num; i++)
{
for (j = 0, pos = (char *)p; j < num - 1; j++, pos += size)
{
if (cmp(pos, pos + size) > 0)
{
memcpy(t, pos, size);
memcpy(pos, pos + size, size);
memcpy(pos + size, t, size);
}
}
}
free(t);
}
int main()
{
char *pos[5] = {"a", "c", "e", "b", "d"};
//qsort(pos, 5, sizeof(pos[0]), strcmp_for_qsort); // in stdlib
quicksort(pos, 5, sizeof(pos[0]), strcmp_for_qsort); //fake
for (int i = 0; i < 5; i++)
puts(pos[i]);
return 0;
}