2

I am trying to sort an array of strings using stdlib qsort. Could anyone point to me the step I am missing.

int compare(const void* a, const void* b)
{
    const char *ia = (const char *)a;
    const char *ib = (const char *)b;
    return strcmp(ia, ib);
}

//utility to print strings
void print_strs(char name[][10],int len){

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

int _tmain(int argc, _TCHAR* argv[])
{
    char names[5][10] = {"norma","daniel","carla","bob","adelle"};
    int size1 = sizeof(names[0]);
    int s2 = sizeof(names)/size1;
    print_strs(names,5);
    qsort(names,s2,sizeof(char),compare);
    printf("\n==================\n");
    print_strs(names,5);
    return 0;
}

Following are the issues in the output :

1.unsorted strings 2.first string of the array is incorrect(Norma printed as amnor).

norma
daniel
carla
bob
adelle
==================
amnor
daniel
carla
bob
adelle
2
  • 1
    Make up your mind about whether you're trying to sort an array of char *s (as your comparison function is defined) or an array of char[10]s (as the array is declared) or an array of chars (according to the size you passed to qsort). Commented Aug 1, 2016 at 1:51
  • sizeof(char) --> size1 Commented Aug 1, 2016 at 1:56

1 Answer 1

1

You are passing wrong size while calling qsort. You are passing sizeof(char) as the size of your individual element, which is wrong. In your case each individual element is a string with ten characters.

So, you can correct that by either calling qsort as:

qsort(names,s2,sizeof(char) * 10,compare); 

Or, as you already have captured this value in size1, you can use that, as:

qsort(names,s2,size1,compare);
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.