1

how can i use qsort to sort alphabetically strings of a 2d array which has strings for a example if i have an array of 4 rows and every row has a string of >=50 characters ...how can i use the qsort function to sort string alphabetically ?

i used this

            qsort(arr, i, 500*sizeof(arr[0]), compare);
            for (j=0; j<i; j++) {
                    printf("%s\n",arr[j]);
            }

and the comparator i used is

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

but it gives me segmentation fault error while trying to compile

9
  • 1
    can you show your definition of arr? Commented Dec 23, 2012 at 19:40
  • 2
    Are you sure it gives you a segmentation fault while trying to compile? It sounds like a compiler bug, which is unlikely. You probably encounter it during run time and not compile time Commented Dec 23, 2012 at 19:40
  • 2
    Should it not be return strcmp(*(char **)a, *(char **)b);? Commented Dec 23, 2012 at 19:40
  • i made a 2d array with strings and i try to sort them alphabetically with qsort command Commented Dec 23, 2012 at 19:41
  • @user1809300 We already know that. Tried what I proposed in my previous comment? Commented Dec 23, 2012 at 19:41

1 Answer 1

4

This way it would work.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 10
int compare (const void * a, const void * b ) {
  return strcmp(*(char **)a, *(char **)b);
}
int main () {
    char *arr[size];
    char buf[1000];
    for (int i=0;i<size;i++) {
      arr[i]=strdup (gets (buf)); // using gets is risky because it can write past buf
    }
    qsort (arr, size, sizeof (char*), compare);
    for (int i=0;i<size;i++) {
      printf ("%s\n", arr[i]);
      free (arr[i]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

however, the idea of 2d arrays got lost. But was'nt clearly defined either.

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.