Search code examples
cstringif-statementc-strings

conditions in if statement in C not working while using &&, despite working separately


My if statement has two conditions. The statement is inside two nested for loops, as follows:

 for(int i = 0; i < LENGTH; i++)
{
    for(char j = 'a'; j <= 'z'; j++)
    {
        if((strcasecmp(&word[0], &j) == 0) && (strlen(word) == i))
        {
            //code here
        }
    }
}

(word is a const char *, length is a constant defined as 45).

If the condition contains only one of these two, it returns true when either of the two conditions are run, so they are both true separately. However, when I put them together like this, it returns false.

Anyone know why this is happening?


Solution

  • The strcasecmp expects a pointer to a null-terminated string for each of its arguments. The first argument is fine, as it is the same as word. The second however is not because you're passing a pointer to a single character. The function will attempt to treat it as a string and read past the memory bounds of the single character. This causes undefined behavior.

    It looks like you really want to compare a single character to one character in the string in a case insensitive way. You can use the tolower function to convert a single character to lower case to compare against a lower case character, and use that on each element of the string:

    if (tolower(word[i]) == j)