I am trying to do a bubble sort on a c-string - see function below. The aim is to sort the characters according to the ASCII code.
The compiler does not complain until run-time at which point I get a segmentation fault. I have run gdb and the program runs fine until line 12. At line 12 the gdb debugger declares 'Process gdb-inferior killed'.
Why is line 12 incorrect? I have come across this issue elsewhere in my program - being unable to assign a character to an element of a c-string. I know that strcpy() is need for string assignment but with specific elements I thought it was ok. Any help MUCH appreciated.
1. void bubblesort(char *str)
2. {
3. int length = strlen(str);
4.
5. for (int i = length - 1; i > 0; i--)
6. {
7. for (int j = 0; j < i; j++)
8. {
9. if (str[j] > str[j + 1])
10. {
11. char temp = str[j + 1];
12. str[j + 1] = str[j];
13. str[j] = temp;
14. }
15. }
16. }
17. return;
18. }