ccharcs50string-literalsequality-operator

I'm not sure why this if statement isn't work


Why isn't this working?

I think the logic in this if statement is flawed but I'm sure exactly what's wrong.

edit: i forgot to add the header files as well as int main(void). everything should be there now

int main(void){
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
string word = "APPPLE";
string alphabet[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", 
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};


    if (word[0] == alphabet[0])
    {
        printf("this program works");
    }
}

                  

Solution

  • The pointer word (string is a typedef for the type char *) points to the first character of the string literal "APPLE".

    string word = "APPPLE";
    

    So the expression word[0] has type char.

    Elements of the array alphabet point to another string literals.

    string alphabet[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", 
    "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    

    and have the type string that is char *.

    In the if statement you are trying to compare a character words[0] with a pointer alphabet[0]

    if (word[0] == alphabet[0])
    {
        printf("this program works");
    }
    

    that does not make a sense.

    What you need is the following

    if (word[0] == alphabet[0][0])
    {
        printf("this program works");
    }
    

    Though it would be better to declare the array alphabet like

    string alphabet = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    

    In this case the if statement will look like

    if (word[0] == alphabet[0])
    {
        printf("this program works");
    }