Kresnik
Kresnik

Reputation: 103

How do a sort a array of void* that points to places with names?

Basically there are rectangles (buildings) and circles (people).

The task I need to do is basically, when a function "fg" is called, every circle that is inside a given radius needs to run to the closest rectangle, and after all the circles inside the radius finds a rectangle, I need to report on a .txt file the names of the circles that run to each rectangle sorted alphabetically.

Such as:

Rectangle A: c1 c2 c3

Rectangle B: c7 c11 c20

...

And so on...

I need to store the addresses of the circles that run, on a vector of each rectangle. I tried to use qsort from stdlib.h, but maybe the function that i use to compare is wrong

(EDIT - full code to better understand):

#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]));
    }  

}

Upvotes: 0

Views: 63

Answers (1)

dbush
dbush

Reputation: 223972

The third parameter needs to be the size of the actual array elements:

qsort(aux, 5, sizeof *aux, myCompare);

Also, since your array elements are of type void *, the pointers passed to the comparison function are pointers to them. So you want:

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

}

Upvotes: 2

Related Questions