Search code examples
cmatrixstrcmp

My strcmp doesn't return 0 when it should


Context : I'm searching for all the words contained in a 2d array (horizontally,vertically and diagonaly).

So what I do is I get all the possible words, check if they're in the given dictionary and if they are store them in an array. The thing is, I don't want it to have duplicates.

Here's a snippet of the code:

        for (i=l-1;i>=0;i--){
            palavra[aux]=mat[i][caux];
            for (j=i;j>=0;j--){
                palavra[aux]=mat[j][caux];
                palavra[aux+1]='\0';
                for (it=0;encontradas[it]!=NULL;it++){
                    if (strcmp(palavra,encontradas[it])==0)flag=1;
                    else flag=0;
                }
                if (flag==0) {
                    r = palavra_existe(dic,palavra);
                    if (r!=0) {
                        found[auxenc]=mystrdup(palavra);
                        auxenc++;
                    }
                }
                flag=0;                 
                aux++;
            }
            aux=0;
        }       

The

    if (strcmp(palavra, found[it])==0)flag=1

line is there to check if the formed worded has been found already, to avoid creating a duplicate. The problem is it doesn't work, duplicates appear anyway (as the flag variable never takes the value 1).

What could I be missing here?


Solution

  • The flag variable does get the value 1, but then it turns back to 0 again in the next iteration.

    Set flag to zero before the loop, and when you find a match you set it to 1 and exit the loop:

    flag = 0;
    for (it = 0; encontradas[it] != NULL; it++) {
      if (strcmp(palavra,encontradas[it]) == 0) {
        flag=1;
        break;
      }
    }
    

    (Exiting the loop isn't needed for the logic to work, but there is no point in looping through the rest of the items once you have found a match.)