Search code examples
cprintfbubble-sort

printf string with "%s" loss character after sort


This is a simple sorting code:

#include <stdio.h>

int main(void) {
    int i, j;
    char str[] = "Hello!! How are you?? I'm Fine. No Thank you.", temp;

    for (i = 0; i < sizeof(str); i++) {
        for (j = i + 1; j < sizeof(str); j++) {
            if (str[i] > str[j]) {
                temp = str[j];
                str[j] = str[i];
                str[i] = temp;
            }
        }
    }

    for(i = 0; i < sizeof(str); i++)
        printf("%c", str[i]);
    printf("%s", str);
}

I found out that I'm able to print the sorted string character by character through for loop but not printf("%s", str);, it wouldn't print anything, can someone tell me why and how to solve this?


Solution

  • You compute the size of your string as sizeof(str). That includes the trailing \0. The byte \0 is guaranteed to end up at the beginning of your sorted string, telling printf that the string is actually empty. You want to leave the terminating NUL past the end of the string, since it is not part of the buffer that you want to sort.

    To sort only the characters of the string, without the terminator, change the loop to

    int n = strlen(str);
    
    for(i = 0; i < n; i++) {
        for(j = i + 1; j < n; j++) {