csortingpointerschar-pointer

Sort function stops working without any errors - C


This program is sorting the strings inside the arrays.

The function Sort is stopping after the 3rd time it runs with no compile errors

int  main(){
   char * arrP1[] = { "father", "mother", NULL };
   char * arrP2[] = { "sister", "brother", "grandfather", NULL };
   char * arrP3[] = { "grandmother", NULL };
   char * arrP4[] = { "uncle", "aunt", NULL };
   char ** arrPP[] = { arrP1, arrP2, arrP3, arrP4 , NULL }; 

   printAllStrings(arrPP);

   sort(arrPP);
   printAllStrings(arrPP);

   
   return 0;
}

void sort(char ** arrPP[]) {
int i, j, n, pi, pj;
int t;
char * temp;

for (n = 0; n < 8; n++) {
    pi = 0;
    pj = 0;
    printf("round %d\n", n);

    for (i = 0; i < (sizeof(arrPP)); i++) {
        for (j = 0; arrPP[i][j] != NULL; j++) {
            t = 0;
            if (i == 0 && j == 0)
                continue;

            while (1) { // checking which word is bigger and switching between them if needed

                if (arrPP[pi][pj][t] == arrPP[i][j][t])
                    continue;

                if (arrPP[pi][pj][t] > arrPP[i][j][t]) {
                    
                    
                    temp = arrPP[pi][pj];
                    arrPP[pi][pj] = arrPP[i][j];
                    arrPP[i][j] = temp;
                    break;
                }
                else {
                    break;
                }
                t++;
            }
            pi = i;
            pj = j;

        }
    }

}
}

output:

(father, mother)

(sister, brother, grandfather)

(grandmother)

(uncle, aunt)

round 0

round 1

round 2

expected output:

(father, mother)

(sister, brother, grandfather)

(grandmother)

(uncle, aunt)

round 0

round 1

round 2

round 3

round 4

round 5

round 6

round 7

(aunt, brother)

(father, grandfather, grandmother)

(mother)

(siter, uncle)


Solution

  • I run your code in a debugger, I didn't really try to see if it works, I only tried to find why you get a infinite loop. The problem is there :

     while (1) 
      { 
          if (arrPP[pi][pj][t] == arrPP[i][j][t])
              continue;
              ...
    

    if the result of the comparison is positive you enter a infinite loop. It happens when comparing grandfather with grandmother.