Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C if condition not working as expected

Tags:

c

syntax

All,

I come from java and php world so this maybe 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 first printf returns in the console "BG01" but for some reason the IF condition doesn't pick up on it and the second printf never gets executed.

What's wrong with this picture?

Thanks, goe

like image 806
goe Avatar asked Nov 30 '22 11:11

goe


1 Answers

The way you are doing it now is that you are comparing 2 pointers instead of the strings they point to. These pointers could point to the same value, but located in very different spots in memory and so be not true.

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

like image 72
Toad Avatar answered Dec 04 '22 02:12

Toad