c - 如何对指向有名字的地方的 void* 数组进行排序?
问题描述
基本上有矩形(建筑物)和圆形(人)。
我需要做的任务基本上是,当调用函数“fg”时,给定半径内的每个圆都需要运行到最近的矩形,并且在半径内的所有圆找到一个矩形之后,我需要报告在 .txt 文件中,运行到每个矩形的圆圈的名称按字母顺序排列。
如:
矩形A:c1 c2 c3
矩形B:c7 c11 c20
...
等等...
我需要将运行的圆圈的地址存储在每个矩形的向量上。我尝试使用 stdlib.h 中的 qsort,但我用来比较的函数可能是错误的
(编辑 - 完整代码以更好地理解):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct wow{
char* name;
}wow_t;
const char* getName(const void* pointer){
const wow_t* aux = pointer;
return aux->name;
}
int myCompare(const void* a, const void* b) {
// setting up rules for comparison
const char* temp1 = getName(a);
const char* temp2 = getName(b);
return strcmp(temp1, temp2);
}
int main() {
wow_t temp[5];
for(int i = 0; i < 5; i++){
temp[i].name = calloc(30, 1);
}
strcpy(temp[0].name, "Joe");
strcpy(temp[1].name, "Daniel");
strcpy(temp[2].name, "Rhuan");
strcpy(temp[3].name, "Drake");
strcpy(temp[4].name, "Peter");
void* aux[5];
for(int i = 0; i < 5; i++){
aux[i] = &temp[i];
}
puts("Before: ");
for(int i = 0; i < 5; i++){
printf("aux[%d] = %s\n", i, getName(aux[i]));
}
qsort(aux, 5, sizeof(const void*), myCompare);
puts("After: ");
for(int i = 0; i < 5; i++){
printf("aux[%d] = %s\n", i, getName(aux[i]));
}
}
解决方案
第三个参数需要是实际数组元素的大小:
qsort(aux, 5, sizeof *aux, myCompare);
此外,由于您的数组元素是 type void *
,因此传递给比较函数的指针是指向它们的指针。所以你要:
int myCompare(const void* a, const void* b) {
// setting up rules for comparison
const char* temp1 = getName(*(const void **)a);
const char* temp2 = getName(*(const void **)b);
return strcmp(temp1, temp2);
}
推荐阅读
- java - 构建项目时缺少课程。exoplayer、ImageIO、BufferedImage
- javascript - 无法从“权限”读取“查询”属性:未启用异步剪贴板标志
- c - 如何在不挂父亲的情况下检索子进程的状态?
- python - 从转储数据中排除 admin.logenty
- adafruit-circuitpython - 在键盘矩阵上使用 adafruit_debouncer
- azure - 从 Azure Function 向 RabbitMQ Docker 容器发送消息
- python - 对另一列python中的每个类别执行多个groupby
- python - 如何从 txt 文件中获取写入的数据
- title - 使flexdashboard的标题变粗?
- typescript - 基于泛型上下文中的泛型参数重命名对象属性