Your issue is in the for loops exit condition, your loops stops before i == 3, which is the last index of your array. Since it never hits that, it never compares your string against the last element, where the "hello" is.
#include <stdio.h>
#include <string.h>
typedef char * string;
int main(int argc, char *argv[]) {
string hello = "hello";
string array[20] = {"e", "cat", "tree", "hello"};
for (int i = 0; i < 4 /* not 3 */; i++) {
if (!strcmp(array[i], hello)) {
printf("Hello is in the array");
}
}
}
And you just learned, first hand, why you should never hard code the count of an array like this. It's inevitable that you'll edit your array, and forget to update the hard-coded count in all the places where you used it.
Try this, instead:
#include <stdio.h>
#include <string.h>
typedef char * string;
int main(int argc, char *argv[]) {
string hello = "hello";
string array[] = {"e", "cat", "tree", "hello"};
size_t array_count = sizeof(array) / sizeof(*array);
for (int i = 0; i < array_count; i++) {
if (!strcmp(array[i], hello)) {
printf("Hello is in the array");
}
}
}
string? Is it justtypedef char * string;?cs50.hstringis indeed achar *, so probably that.< 3to<= 3or< 4. I assume this is just a typo, right?