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");
}
}
The pointer word (string is a typedef for the type char *) points to the first character of the string literal
"APPLE"
.So the expression
word[0]
has typechar
.Elements of the array
alphabet
point to another string literals.and have the type
string
that ischar *
.In the if statement you are trying to compare a character
words[0]
with a pointeralphabet[0]
that does not make a sense.
What you need is the following
Though it would be better to declare the array alphabet like
In this case the if statement will look like