0

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?

MWE:

#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

1 Answer 1

2

Simply

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.