c - 在包含字符串的结构上使用 qsort

标签 c arrays struct qsort

我想在我的程序中使用 qsort() 函数。

我想按字符串对这个结构进行排序。

我只是提出了建议。

我在网上搜索过,但没有找到。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int cmpstr(const void* a, const void* b)

{
    const char* aa = *(const char**)a;
    const char* bb = *(const char**)b;
    return strcmp(aa,bb);
}

typedef struct
{   int x;
    char a[10];

}alex;
int main()
{
    alex vd[10];
int i;
//vd=malloc(sizeof(struct alex)*2);
strcpy(vd[0].a,"dinamitte");
strcpy(vd[1].a,"alex");
printf("Before : \n");
for(i=0;i<=1;i++)
    printf("%s ",vd[i].a);

//qsort(v,1,sizeof (v) ,myCompare);
int n=2;
//qsort(v, 2, sizeof (char *), cstring_cmp);
qsort(vd,n  ,sizeof(alex),cmpstr);
//qsort()
printf("\nAfter : \n");
for(i=0;i<=1;i++)
    printf("%s \n",vd[i]);
    return 0;
}

编译后,它会在屏幕上写入“dinamitte”和“alex”,然后是一些奇怪的字符。

最佳答案

像这样修复:

typedef struct {
    int x;
    char a[10];
} alex;

int cmpstr(const void* a, const void* b){
    const alex *aa = a;
    const alex *bb = b;
    return strcmp(aa->a, bb->a);
}

还有printf("%s \n",vd[i]);错字为 printf("%s \n",vd[i].a);

关于c - 在包含字符串的结构上使用 qsort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40948444/

相关文章:

c - 操作系统 - 进程

javascript - 在对象上使用 jQuery grep

c - 从C开始,结构和函数简单程序,返回数据可能错误

json - 在 go 中覆盖结构标签

c - 将字符串解析为 argv/argc

c - strncat 添加了一些意外的字符

c - 何时释放资源 - 奇怪的情况

python - 将数组中的元素转换为python中的 float

java - 遍历 Arraylist<String[]>

c - 持续错误 : subscripted value is neither array nor pointer nor vector