Stack Exchange
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.

if(s1[i] < s2[i])   return 0;  should be if(s1[i] < s2[i])   return -1;. Also note that aaa will compare equal to aaax with the current compare method.

The bulk of the compare() function should just be a call to strcmp(). Aso, don't cast the return value of malloc() in C.

qsort()'s comparator should return to it <0 if the left/right elements sort ascending, 0 if they are equal, and >0 if they sort descending. I don't think you can get away with only returning 1 or 0. I mention this because your question comes up quite high in related search results.

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


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


What you're saying is graspable but char *s1 = (char*)a, *s2 = (char*)b works just fine.

+1, this is of course correct. No point in dropping const from the arguments, though.
