kBisla
kBisla

Reputation: 640

qsort comparison function not working

I need to sort an array of strings, taken as input. Help me with the pointers here please.

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

int compare(const void *a, const void *b){
    char* s1 = (char*)a, s2 = (char*)b;
    int len1 = strlen(s1), len2 = strlen(s2);
    int i=0;
    for(i=0; i< len1 && i<len2; i++){
        if(s1[i] > s2[i])   return 1;
        if(s1[i] < s2[i])   return 0;
    }
    return 0;   
}

int main() {
    int i;
        int len;
        scanf("%d",&len);
        char* a[len];
        for(i=0; i<len; i++){
            a[i] = (char*)malloc(13);
            scanf("%s",a[i]);
        }
        qsort(&a, len, sizeof(char*), compare);
        for(i=0; i<len; i++){
            printf("%s\n",a[i]);
        }

    return 0;
}

The problem is with the compare function only.

Upvotes: 0

Views: 361

Answers (2)

Barmar
Barmar

Reputation: 780798

char* s1 = (char*)a, s2 = (char*)b;

declares s1 as a pointer and s2 as a char, because * binds to the variable on the right, not to the type on the left. You need to write:

char *s1 = *((char**)a), *s2 = *((char**)b);

The compiler should have given you a bunch of warnings and errors about s2 because of this. When I tried to compile your code, I got:

testsort.c: In function 'compare':
testsort.c:6: warning: initialization makes integer from pointer without a cast
testsort.c:7: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast
testsort.c:10: error: subscripted value is neither array nor pointer
testsort.c:11: error: subscripted value is neither array nor pointer

With these correction, the program compiles cleanly and runs correctly:

$ ./testsort
5
abc
12345
foo
aaa
bbb

Output:

12345
aaa
abc
bbb
foo

Upvotes: 3

Baldrick
Baldrick

Reputation: 11840

Your data array is an array of char * , so the comparison method gets passed 'pointers to pointers' (char**) by qsort.

You need:

char *s1 = *((char**)a), *s2 = *((char**)b);

Upvotes: 3

Related Questions