2

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?

2
  • 6
    Literal strings in C are read only. Attempting to modify them leads to undefined behavior. Commented Aug 31, 2017 at 11:37
  • "I would like to sort characters in in each of those strings." --> and where would you like to put that sorted string given that writing to the source string, a string literal, is undefined behavior? Commented Aug 31, 2017 at 13:09

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

How do you know that those strings are read-only? Could you show me code example which can fix that? I've checked that after declaring char tab[]="dafafa" instead of char* tab="dafafa" it worked. Whats the difference there?
@PiotrWitkoś All string literals are read-only, in the sense that you are not allowed to change their content. char tab[]="dafafa" is different, because you initialize an array of characters with a string literal. This array becomes writable. TAB[3] in your original code is an array of pointers, so it is very much like char* tab="dafafa" repeated three times. You can check here to see how to properly copy strings.
I have a question in my exam to sort characters in every string in an array of strings TAB[100]. How would you declare it to avoid copying the content?
@PiotrWitkoś char TAB[3][100]={"dafafa","alfkasf","bafgr"}; will do the trick (demo).

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.