0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int i,j;
    char temp[10];

    char **A;

    A=(char**)malloc(10*sizeof(char*));

    for(i=0;i<10;i++)
        A[i]=(char*)malloc(100*sizeof(char));

    printf("Enter the words you would like to sort :\n");
    for(i=0;i<10;i++)
        gets( *A );

    for(i=0; i < 10 ; i++)
    {

        {
            if(strcmp(A[i],A[i+1]) > 0)
            {
                strcpy(temp,A[i]);
                strcpy(A[i],A[i+1]);
                strcpy(A[i+1],temp);
            }
        }
    }

    for (i = 0; i < 10; i++)
        printf("%s\n", A[i]);         

    return 0;
}

I am trying to write a C program that sorts a given list of 10 strings in alphabetical order. The program takes all of the strings but then it freezes and doesn't sort them. Can anyone tell me where I am going wrong? Thank you in advance.

3
  • 3
    gets( *A ), do you mean gets( A[i] )? Commented Nov 16, 2014 at 14:15
  • Yea I have changed it but when I compile the program i'm still getting the same error. Commented Nov 16, 2014 at 14:17
  • 2
    if(strcmp(A[i],A[i+1]) > 0) : a[i+1] out of bounds when i is 9. Commented Nov 16, 2014 at 14:19

1 Answer 1

3

Your gets(*A) overwrites previous input. You should use gets(A[i]) instead.

Also you should use c builtin sorting fun for it: qsort(A,sizeof(char*),10,strcmp); instead of manual bubbling.

If you want it to do manualy, instead of copying strings you should simply swap pointers to them.

for (int i=0; i<9; i++)
{
    for (int j=i+1; j<10; j++)
        if (strcmp(A[i],A[j])>0)
        {
            char* t=A[i];
            A[i]=A[j];
            A[j]=t;
        }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I didn't want to revert to the built in sorting function. Instead I want to try doing it manually.
How would I implement qsort in this condition?
You could sort pointers to strings using strcmp comparator function.
And to print them out I used for (i = 0; i < 10; i++) printf("%s\n",A[i]); , but I didn't get the sorted list back.

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.