0

i am trying to make a program that inserts to an 'char** arr' a char pointer and then sort the char pointers with strcmp but for some reason its just don't work, the code i added is the sorting part of the entire code.

do
    {
        flag = 0;

        for (i = 0; i < num - 1; i++)
        {
            if ((strcmp(arr[i], arr[i + 1])) < 0)
            {
                flag = 1;
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }

            else if ((strcmp(arr[i], arr[i + 1])) > 0)
            {
                flag = 1;
                temp = arr[i + 1];
                arr[i + 1] = arr[i];
                arr[i] = temp;
            }

            else if ((strcmp(arr[i], arr[i + 1])) == 0)
            {
                flag = 1;
                continue;
            }
        }
    } while (flag == 1);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Ofek Ezon
  • 29
  • 1
  • 5

1 Answers1

0
  1. Depends on whether you want ascending order or descending order, you should only swap arr[i] and arr[i+1] in one of the if cases. (either strcmp() < 0 or strcmp() > 0 case)
  2. flag should only be assigned as 1 when swapping actually happens. Otherwise the loop won't stop.
timrau
  • 22,578
  • 4
  • 51
  • 64