1

I have the following code:

#include <stdio.h>

void insertion_sort(char[], int);
void swap(char*, char*);

int main() {
    char s[] = "hello world";
    puts(s);
    insertion_sort(s, sizeof(s)/sizeof(char));
    puts("done\n");
    puts(s);
    return 0;
}

void swap(char* a, char* b) {
    char tmp = *a;
    *a = *b;
    *b = tmp; 
}

void insertion_sort(char s[], int n)
{
    int i,j;
    /* counters */
    for (i=1; i<n; i++) {
        j=i;
        while ((j>0) && (s[j] < s[j-1])) {
            swap(&s[j],&s[j-1]);
            j = j-1;
        }
        printf("%s\n", s);
    }
}

The problem is, after the insertion_sort() function call, s becomes empty - puts(s) prints nothing.

Please advise.

7
  • 4
    The NUL terminator of the string is put in front. That's the reason. Commented Jul 11, 2012 at 7:49
  • 1
    You don't need an IDE for debugging - you can just use gdb directly. Commented Jul 11, 2012 at 7:53
  • 1
    Use a command line debugger then. Commented Jul 11, 2012 at 7:53
  • 1
    Or use printf() debugging. Though I'd suggest trying gdb first. Commented Jul 11, 2012 at 8:22
  • 1
    I tried debugging and found that null terminating character '\0' was placed to the beginning of the string. And that caused puts to not print anything. Although I couldn't see what's going on inside puts, because it's defined in c library, Information I got was quite sufficient to understand the problem. Thanks. Commented Jul 11, 2012 at 10:50

2 Answers 2

8

Change:

insertion_sort(s, sizeof(s)/sizeof(char));

to:

insertion_sort(s, strlen(s));

otherwise you will be including the '\0' terminator of s[] in your sort.

Note that you will need an additional header for strlen so change:

#include <stdio.h>

to:

#include <stdio.h>    // printf etc
#include <string.h>   // strlen etc
Sign up to request clarification or add additional context in comments.

2 Comments

strlen is located in string.h so don't forget to #include<string.h>
@Zekian: thanks - good point - I have now updated the answer to cover this.
3

The problem is that the length that you pass to insertion_sort includes terminating \0 character, which happens to have value 0, so in sort it is placed as the first element of your array. This is why your last puts() prints nothing - because the first character is now "the end of a string".

I suggest you to calculate the size of a string using strlen() which will return the length of a string excluding terminating character. Or if you want to do it your way, take terminating character into consideration and substract it from the total length.

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.