-1

I am trying to do my lab sheet related to string, array and pointer. The problem is to "to sort 5 string words stored in an array of pointers."

I tried a lot and also searched the solution for the problem in various sites. I have been able to sort the strings alphabetically but is always some part of the other string at the end of a string.

like If I entered strings like laptop and comp then the output will be comptop and laptop

The main code is:

main()
{
char *str[10], *t;
int i,j;

for(i=0;i<5;i++)
{
    scanf("%s",&str[i]);
}

for(i=0; i<5; i++)
{
    for(j=i+1; j<5; j++)
    {
        if (strcmp(&str[j-1], &str[j]) > 0)
        {
            t=str[j];
            str[j]=str[j-1];
            str[j-1]=t;
        }
    }
}
printf("\n");

for(i=0;i<5;i++)

{
    printf("%s\n",&str[i]);
}
}
basanta
  • 363
  • 1
  • 3
  • 8
  • I know C can be an obtuse language, but your variable names really don't help convey any meaning to this code. – Claies Mar 20 '15 at 03:14

1 Answers1

2

The following line is cause for undefined error.

scanf("%s", &str[i]);

Problems:

  1. Type of str[i] is char*. Type of &str[i] is char**. The compiler should warn you that it is the wrong type to use with the given format, %s.

  2. Reading a string into that address will corrupt your stack and will lead to undefined behavior.

Syntactically speaking, you can use

scanf("%s", str[i]);

but that will be problem unless you allocate memory for the string.

You can allocate memory for the string on the heap or the stack. For the time being let's assume you don't intend to hold more than 99 characters in your string.

To use memory from the stack:

char str[10][100], *t;
int i,j;

for(i=0;i<5;i++)
{
    scanf("%99s", str[i]);
}

To use memory from the heap:

char* str[10], *t;
int i,j;

for(i=0;i<5;i++)
{
    str[i] = malloc(100);
    if ( str[i] != NULL )
    {
       scanf("%99s", str[i]);
    }
}

Make sure to call free() when you are using memory from the heap.

The line

    if (strcmp(&str[j-1], &str[j]) > 0)

is incorrect because type of &str[j-1] and &str[j] is char**. Once again, you should have received warnings from the compiler about that. That line needs to be:

    if (strcmp(str[j-1], str[j]) > 0)

The block:

    {
        t=str[j];
        str[j]=str[j-1];
        str[j-1]=t;
    }

will work only if you use memory from the heap. If you use memory from the stack, you'll need to use strcpy() to move the data between the elements of str.

The line

printf("%s\n",&str[i]);

should be

printf("%s\n", str[i]);

By this time, you should know why.

R Sahu
  • 204,454
  • 14
  • 159
  • 270