2

Overall arrays in C are very confusing to me, so I have absolutely no idea of how to do this. Here is an example of what I am trying to do.

string hello = "hello";
string array[20] = {"e", "cat", "tree", "hello"};

for (int i = 0; i < 3; i++) {
    if (!strcmp(array[i], hello)) {
        printf("Hello is in the array");
    }
}

3
  • 3
    What's the definition of string? Is it just typedef char * string;? Commented Jun 2, 2021 at 19:34
  • 2
    @Alexander OP has tagged the question with cs50, and I think in cs50.h string is indeed a char *, so probably that. Commented Jun 2, 2021 at 19:37
  • Apart from the strangeness of initializing an array of 20 things with just 4 values, this can be corrected by changing < 3 to <= 3 or < 4. I assume this is just a typo, right? Commented Jun 2, 2021 at 20:12

1 Answer 1

2

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");
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

To clarify: array_count is calculated by dividing the size of array, which is an array of four pointers to char, with the size of *array, which is one pointer to char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.