C if the condition is not working properly

Everything,

I come from java and php world, so this can be a factor. But I have a problem with:

printf("%s\n",data[0]); if(data[0] == "BG01") { printf("%s\n",otherstring); } 

The problem is that the first printf returns to the "BG01" console, but for some reason the IF condition does not pick it up, and the second printf will never be executed.

What is wrong with this image?

Thank u

+4
source share
2 answers

In C, you should use strcmp() , just like you should use .equals() in Java:

 if (strcmp(data[0], "BG01") == 0) ... 
+8
source

The way you do it now is that you are comparing 2 pointers instead of the lines they are pointing to. These pointers can point to the same value, but are located in very different places in memory, and therefore are not true.

The way to do this is to use the strcmp (string1, string2) function, which will check the strings themselves, not the pointers.

+12
source

All Articles