0

I have the following code:

void sortStrings(char strings[5][32])
{
    int i = 0, j = 0, wall = 0;
    int min = i;
    for (int i = wall; i < 5; i++){
        min = i;
        for (j = wall; j < 5; j++){
            if (strcmp(strings[j], strings[min]) < 0){
                min = j;
            }
        }
        swapStrings(strings[min], strings[wall]); 
        wall++; 
    }
}

What this code does is sorts a 2d array of strings by alphabetical order, I have tested it and it works correctly, now my question is how could I implement this code WITHOUT using array operations (aka using pointers and pointer operations only).

This is what I have so far and it is crashing when I try to run it so what am I doing wrong?

{
    int i = 0, j = 0, wall = 0;
    char *p = strings;
    int min;
    for (i = wall; i < 5; i++){
        min = i;
        for (j = wall; j < 5; j++){
            if (*(p + j) < *(p + min)){
                min = j;
            }
        }
        swapStrings(*(p + j),*(p + wall)); 
        wall++; 
    }
}

Here is the swapStrings method I am using for reference:

void swapStrings(char string1[], char string2[])
{
    char temp[32];
    strcpy(temp, string1);
    strcpy(string1, string2);
    strcpy(string2, temp);
}

The expected output is: if I were to enter in 5 strings, lets say they are:

hello
goodbye
how
are
you

It should return:

are
goodbye
hello
how
you

Thank you.

YoungDanEn
  • 27
  • 1
  • 8
  • Put the function signature in your pointer example, otherwise we have no idea how you want it to work. Also, why the 5 - do you want that dimension always to be size 5, or should you be passing in a parameter with the size (in your missing function signature)? etc. – underscore_d Feb 15 '16 at 00:25
  • `char *p = strings;` is invalid since the object strings was a two-dimensional array. Check out this answer: http://stackoverflow.com/questions/7586702/is-2d-array-a-double-pointer – Tony Ruth Feb 15 '16 at 00:26

1 Answers1

0

You have two things wrong:

  1. p have to be char** and not char*
  2. Comparing yourself between strings need a loop such:

    int t = 0;
    while (*(*(p + j)+t) &&  (*(*(p + j) + t) == *(*(p + min) + t)))
        t++;
    if (*(*(p + j) + t) < *(*(p + min) + t)) {
        min = j;
    }
    

    Maybe you want to write your function for compare.

zardav
  • 1,160
  • 3
  • 12
  • 22