#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    2

    Why doesn't qsort() work ?


    I've written an array of pointers, each pointing to a word.

    Then i use qsort to put the array into alphabetical order, but qsort doesn't work and the array is printed as given(WHY?):
    Code:
    #include <stdlib.h>
    #include<string.h>
    #include<stdio.h>
    
    char *array[]={"cat", "apple", "world", "hello"};
    
    int compare(const void* a, const void* b)
    {
        if( (stricmp((char*)a, (char*)b) ) < 0 ) return -1;
        if( (stricmp((char*)a, (char*)b) ) == 0 ) return 0;
        if( (stricmp((char*)a, (char*)b) ) > 0 ) return 1;
    }
    
    
    int main()
    {
        qsort(array, 4, sizeof(char*), compare);
        
        int i;
        for(i=0; i<4; ++i)
            printf("%s\t", array[i]); 
            
        getch();
        return(0);
    }
    I basically sort the array of pointers, then print the words thru those pointers.
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    It's because your compare function is wrong.

    Recall from your other thread that the compare function receives pointers to two elements of the array.

    Since your array is composed of pointers, you in fact receive pointers to pointers.
    Code:
    #include <stdlib.h>
    #include<string.h>
    #include<stdio.h>
    
    char *array[]={"cat", "apple", "world", "hello"};
    
    int compare(const void* a, const void* b)
    {
      char * const *pa = a;
      char * const *pb = b;
      return strcmp(*pa,*pb);
    }
    
    
    int main()
    {
        qsort(array, 4, sizeof(char*), compare);
        
        int i;
        for(i=0; i<4; ++i)
            printf("%s\t", array[i]); 
            
        return(0);
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    2
    It worked. :cheers:

    Thank you !

IMN logo majestic logo threadwatch logo seochat tools logo