c - Qsort结构数组比较函数

标签 c struct qsort

好吧,我通过在网上四处寻找来解决这个问题,但是有人可以解释第 1 行和第 2 行的确切作用以及为什么需要它们

int structCompare(const void *a, const void *b)
{
     struct trade *tempA = (struct trade *)a;//(1)
     struct trade *tempB = (struct trade *)b;//(2)
     return strcmp(tempA->name, tempB->name);
}

最佳答案

这些行将通用 void 指针转换为 struct trade 指针。当涉及 void * 时,显式强制转换在 C 中是多余的,应该被删除:

 struct trade *tempA = a;
 struct trade *tempB = b;
 return strcmp(tempA->name, tempB->name);

你可以这样写:

return strcmp(((struct trade *)a)->name, ((struct trade *)b)->name);

不过我更喜欢第一个。

关于c - Qsort结构数组比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10760475/

相关文章:

c - 到达指向 C 中结构的指针

objective-c - 奇怪的是,为什么我的 abs 函数返回 -0?

c - c 中是否允许在另一个结构中定义结构?

c - 使用 C 中的 openmp,如何并行化包含用于 qsort 的嵌套比较函数的 for 循环?

C——无限循环,我想?

c - 判断两个三角形是否全等

c++ - 如何在 QML 中创建 Q_GADGET 结构的新实例?

c - c中的全局结构(初始化元素不是编译时常量)

c - c 中的段错误(核心转储)

c - 对绑定(bind)结构元素进行排序