Search code examples
cstringpointersbubble-sort

Bubble sort function for strings causes program crashes


I don't know what's happening, every time I enter the second string in the code below, an error box pops up. I am using Codeblocks as compiler. Is it because I use pointer to pointer?

#include<stdio.h>
#include<conio.h>
void sort_string(char **) ;
void main()
{
    char *name[5] ;
    int x =0;
    printf("Enter Names");
    for(x = 0 ; x < 5 ; x++)
    {   fflush(stdin);
        fgets( name[x], 100,  stdin);
    }
    sort_string(name);
    for( x = 0 ; x < 5 ; x++)
    {
        puts(name[x]);

    }


}
void sort_string(char *name[5])
{
    char *temp;
    int i , j ;
    for ( i = 4 ; i >=0; i--)
    {
        for ( j = 0 ; j <=i; j ++  )
        {
            if(strcmp(name[j] > name[j+1]))
            {
                temp = name[j+1];
                name[j+1] = name[j];
                name[j] = temp;
            }
        }
    }
}

Solution

  • As noted in comments on the question, you need to allocate memory for the name elements. One easy way is to note that you hard-code the length of a name to 99 chars (the limit passed to fgets) and change your array to

    char name[5][100];
    

    Once you do this, your string comparison isn't quite right. Can you change

    if (strcmp(name[j] > name[j+1]))
    

    to

    if (strcmp(name[j], name[j+1]) > 0)
    

    This will show up another bug. Your inner loop can run until j=4. You then read/write beyond the end of your array when you access name[j+1]. The easiest fix here will be to change the inner loop to exit one iteration sooner

    for (j=0 ; j<i; j++)
    //          < rather than <=