1

I'm trying to set up a comparison between an array and a given string. The idea being, that if i started building structures with multiple objects in them, that i could test for a key word in said structure and set up a counter to see how often that element is contained within that structure.

Though this doesnt seem to work, as the terminal output i get is the "ohnoo". Hence I'm thinking that there is something wrong with the comparison in line 8.

The compiler sees nothing wrong with the following code, so its hard to find a solution by myself.

Here's a simple piece of code i tried to test this idea with.

#include <stdio.h>
#include <string.h>

char string1[10] = "Automatic";

int main()
{
    if(string1 == "Automatic")
    {
        printf("huzzah\n");
    }
    else{
        printf("ohnoo\n");
    }
}
mr. yoxon
  • 13
  • 3

1 Answers1

0

Strings in C cannot be compared in this way. Rather use strcmp. Otherwise, using == you are determining if they point to the same location in memory, rather than whether their contents are the same.

#include <stdio.h>
#include <string.h>

char string1[10] = "Automatic";

int main()
{
    if (strcmp(string1, "Automatic") == 0)
    {
        printf("huzzah\n");
    }
    else{
        printf("ohnoo\n");
    }
}
Chris
  • 26,361
  • 5
  • 21
  • 42