• C

sort inputted strings

I am trying to read in up to five strings and print them in alphabetical order. I have no idea what I am doing wrong. Also, the input does not terminate when nothing is entered like I want it to do. My program fails after it prints the unsorted strings! any help would be appreciated  



 /*============================================================
//
// This program reads in up to five strings and sorts them
//
//============================================================
*/

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

void print_string_array(char * string_array[], int length);
void sort(char* string_array[], int length);
void exchange(char** pStr1, char** pStr2);

    int main (void)
    {
    int length;
    char str1[1000];
    char str2[1000];
    char str3[1000];
    char str4[1000];
    char str5[1000];
    char * string_array[5] = {str1, str2, str3, str4, str5};

       
    printf ("\nPlease enter up to 5 strings\n");
    printf ("Enter a null string to indicate completion.\n");

      printf ("1: ");
      scanf("%999s", str1);
      if(str1 == NULL)
                {
                    length = 0;
                 }
      printf ("2: ");
      scanf("%999s", str2);
               if(str2 == NULL)
               {
                   length = 1;
               }
      printf ("3: ");
      scanf("%999s", str3);
                if(str3 == NULL)
                {
                     length = 2;
                }
      printf ("4: ");
      scanf("%999s", str4);
                if(str4 == NULL)
                {
                     length = 3;
                 }
      printf ("5: ");
      scanf("%999s", str5);
                if(str5 == NULL)
                {
                    length = 4;
                }

         else
         {
             length = 5;
                }


    if(length == 0)
    {
        printf("No strings were entered!");
        return 1;
    }
         printf("length is %d\n", length);

    printf("Before sort\n");

    print_string_array(string_array, length);
    sort(&string_array, length);


    printf("After sort\n");
    print_string_array(string_array, length);
    printf("\nNormal Termination.");
    return 0;
    }

/*============================================================
// This function exchanges two integers.
//============================================================
*/
    void exchange(char** pStr1, char** pStr2)
    {
        char * temp = *pStr1;
        *pStr1 = *pStr2;
        *pStr2 = temp;
    }

/*============================================================
// This function sorts an array of integers
//============================================================
*/
    void sort(char* string_array[], int length)
    {
        int exchange_done;
        int i;
        int j;

        do
        {
            exchange_done = 0;
            for (i = 0; i < length; i++)
            {   j = i + 1;
                if (strcmp(string_array[i], string_array[j])< 0)
                {
                    exchange(&string_array[i], &string_array[i+1]);
                    exchange_done = 1;
                }
            }
        } while (exchange_done);
    }



/*============================================================
// This function prints the string array.
//============================================================
*/

    void print_string_array(char * string_array[], int length)
    {
        int i;
        for(i = 0; i < length; i++)
        {
            printf("%d: %s \n", i+1, string_array[i]);
        }
    }
mwinfielAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kent OlsenDBACommented:
Hi mwinfiel,

The first thing that you need to do is take the definitions for str1, str2, str3, str4, str5, and string_array out of the main function and put them into the globals block.  (Out of any function.)  As you've defined them, they are stack variables that are allocated at run time.  However, your definition of string_array attempts to initialize the array at compile time.  Obviously you can't initialize the address at compile time when the address isn't defined until run time.

That'll get you a good start!


Good Luck!
Kent
PaulCaswellCommented:
Your problem is here:

    sort(&string_array, length);

You are passing the address of the address of the array! You should just pass the array, which is a pointer in itself.

try changing it to:

    sort(string_array, length);
 
Paul

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mwinfielAuthor Commented:
Paul,   I tried that but my program still fails....
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

PaulCaswellCommented:
Hi mwinfiel,

OK! What actually goes wrong?

Paul
mwinfielAuthor Commented:
the program  fails (exits) right after the unsorted output is printed.
Kent OlsenDBACommented:
Hi mwinfiel,

Look in the sort routine.  Two problems with it.  1)  It won't really sort.  2)  You're testing the values of string_array at *i* and *j* but passing the values at *i* and *i+1* to swap().  You're over-indexing the array.


Kent
PaulCaswellCommented:
Hi mwinfiel,

It may be:

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

You are stepping off the end of the array! Since you are comparing array[i] with array[i+1].

Try:

            for (i = 0; i < length-1; i++)

Still checking!

Paul
mwinfielAuthor Commented:
I figured out one problem I forgot the & in

if (strcmp(&string_array[i], &string_array[j])< 0)

I am still having a problem though... I am supposed to prompt the user to input up to five strings. When the user is finished entering strings... they are supposed to enter a null string which I am assuming is the return. but, my program won't stop input by entering return
PaulCaswellCommented:
Hi mwinfiel,

That works here now (dont forget Kent's point about swap)! It sorts in reverse order but I am sure you'll crack that one!

Good code for a newbie!

Paul
Kent OlsenDBACommented:
Hi mwinfiel,

That's because of the new-line character at the end of each string.  Change the format string to "%999s\n" and you should be fine.


Kent
deepu chandranCommented:
hi friend,
 void sort(char* string_array[], int length)
    {
        int exchange_done;
        int i;
        int j;

        do
        {
            exchange_done = 0;
            for (i = 0; i < length; i++)
            {   j = i + 1;
                if (strcmp(string_array[i], string_array[j])< 0)
                {
                    exchange(string_array[i], string_array[i+1]);// currect like this i think it will work
                    exchange_done = 1;
                }
            }
        } while (exchange_done);
    }

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.