Strange qsort behaviour on dynamic array of struct pointers

Hi,

in the below code i am initializing a dynamic array of struct Foo*,
start initializing the pointers and setting an index variable for sorting.
qsort is getting the sort oder wrong, until i remove members muh2-muh4 from the struct.

Can someone explain what is going wrong here ?
Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>

struct Foo {
    int muh;
    int muh2;
    int muh3;
    int muh4;
    int index;
};

struct Foo** foos;

int foocomp(const void* a, const void* b) {

    struct Foo* f1 = (struct Foo*) a;
    struct Foo* f2 = (struct Foo*) b;

    if (f1->index > f2->index) {
        return 1;
    } else if (f1->index == f2->index) {
        return 0;
    }

    return -1;

}

int main(int argc, char** argv) {

    int count = 10;
    foos = (Foo**) malloc(count * sizeof (struct Foo*));

    int i;
    for (i = 0; i < count; i++) {
        foos[i] = (Foo*) malloc(sizeof (struct Foo));
        foos[i]->index = i;
    }

    qsort(foos, count, sizeof (struct Foo*), foocomp);

    for (i = 0; i < count; i++) {
        printf("%d ", foos[i]->index);
    }

    return (EXIT_SUCCESS);
}


The output is: 0 1 2 8 9 7 5 6 3 4

Last edited on
qsort passes pointers to array elements to comparison function. YOu have pointer to Foo as your array element. So actual type of a and b is Foo**.

Fix:
1
2
3
4
5
int foocomp(void* a, void* b) {

    struct Foo* f1 = *(struct Foo**) a;
    struct Foo* f2 = *(struct Foo**) b;
//... 
Argh, thank you very much for clearing this up, now it's making sense!
Shouldn't have missed that, thanks for the quick response.
Topic archived. No new replies allowed.