René G René G - 5 months ago 20
C Question

Why doesn't qsort() work when I use it to sort an array of strings?

I'm trying to sort this list of strings: ["a", "z", "b"]. So the answer should be ["a", "b", "z"]. However, when I try to use C's qsort(), nothing moves! What am I doing wrong?


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

int sortcmpfunc (const void *a, const void *b)
{ return strcmp((const char*)a, (const char*)b); }

int main(){
const char** list = (const char**)malloc(50*sizeof(const char*));
for(int i = 0; i < 50; i++){
list[i] = (char*)malloc(50*sizeof(char));

list[0] ="a";
list[1] = "z";
list[2] = "b";

for (int i=0; i<3; i++){ printf("%s ", list[i]); } printf("\n");
qsort(list, 3, sizeof(const char*), sortcmpfunc);
for (int i=0; i<3; i++){ printf("%s ", list[i]); } printf("\n");

return 0;

Output with
gcc test-qsort.c && ./a.out

a z b
a z b



strcmp(*(char **) a, *(char **) b);

note that a pointer to each element is passed to the comparison function, hence you need to cast to the correct type and dereference.

And please avoid

for (int i=0; i<3; i++){ printf("%s\n", list[i]); }

and instead write

for (int i = 0; i < 3; i++) {
    printf("%s\n", list[i]);

it's horrible

And also use

gcc -Wall -Werror test-qsort.c && ./a.out