Jun 28

strcmp_for_qsort和挂羊头卖狗肉的qsort 不指定

felix021 @ 2010-6-28 22:14 [IT » 程序设计] 评论(0) , 引用(0) , 阅读(4177) | Via 本站原创 | |
对字符指针数组使用qsort排序时,strcmp强制类型转换后不能直接用于qsort, 需要进一步的纠结的。包装……
p.s. 对于字符串数组char a[100][100]; 就可以用strcmp。
#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;
}




欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]