首页 > 解决方案 > 如何对指向有名字的地方的 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]));
    }  

}

标签: cqsort

解决方案


第三个参数需要是实际数组元素的大小:

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);

}

推荐阅读