kajfhk
kajfhk

Reputation: 43

issue with qsort in c

I have a structure like this :

typedef struct item{
    char label[10];
    int support;
};

I created an array of such structures like this :

struct item* finstr = (struct item*)malloc(sizeof(struct item)*10);

I filled the array with appropriate values and want to sort the array according to the values of 'support', using the qsort function. But, the array is not getting sorted at all. The output is coming out to be the same as input.

here is the call to the qsort function and the code for the 'comparator' function :

qsort((void*)finstr,(sizeof(finstr)/sizeof(finstr[0])),sizeof(finstr[0]),comparator);

comparator function :

int comparator(const void* i1,const void* i2) {
    int l = ((struct item*)i1)->support;
    int r = ((struct item*)i2)->support;
    return l-r;
}

I do not understand where I am making the mistake. Any help is greatly appreciated.

Thanks in advance.

Upvotes: 0

Views: 72

Answers (2)

R Sahu
R Sahu

Reputation: 206607

The expression (sizeof(finstr)/sizeof(finstr[0])) does not give you the number of elements unless finstr is an array. In your case, it evaluates to sizeof(void*)/sizeof(struct item), which is most likely 0.

Replace it with 10.

Excellent advice from @ForhadAhmed:

Its good practice to replace the 10 in malloc(sizeof(struct item)*10) and the size of the array passed to the qsort function with a macro or a variable so that you don't accidentally call qsort with a different sized array than what you intended.

Upvotes: 1

Alex Reynolds
Alex Reynolds

Reputation: 96937

Try building and running the following, to see what answer you get:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char bar[123];
    int baz;
} foo;

int main(int argc, char** argv) {
    foo *foo_ptr = malloc(sizeof(foo) * 1000);
    fprintf(stdout, "%zu\n", sizeof(foo_ptr));
    fprintf(stdout, "%zu\n", sizeof(foo_ptr[0]));
    free(foo_ptr);
    return 0;
}

Depending on architecture, you may notice that sizeof(foo_ptr) is eight bytes — the size of the foo pointer called foo_ptr. Compare this with the value of sizeof(foo_ptr[0]). This should provide a hint at what is wrong.

Upvotes: 0

Related Questions