C char qsort in array of pointers to strings

148 views Asked by At

I have an array of pointers to string:

char *TAB[3] = { "dafafa", "alfkasf", "bafgr" };

I would like to sort characters in in each of those strings.

My compare function:

int cmp(const void *a, const void *b)
{
   return *(char *)a - *(char *)b; 
}

and while trying qsort on one of these:

qsort(TAB[0], 6, sizeof(char), cmp);

The program doesn't work. After many efforts I found that the reason of the problem is in delivering TAB[0] to qsort().

Can anyone explain why it doesn't work and how to fix that?

1

There are 1 answers

4
Sergey Kalinichenko On BEST ANSWER

If you want to sort characters inside each string, the first thing you must ensure is that your strings can be written to. As it currently stands, your strings are read-only, so you cannot sort their characters without copying their content into memory that allows writing.

Next thing is that you need a loop. Since you are sorting each string individually, you need to loop through the array, and call qsort on each item. The initial item is TAB[i], and the length is strlen(TAB[i]). Your cmp function will work.