Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Comparison of Arrays with == works, why? [duplicate]

I'm a little bit confused. I have the following function:

int comp(char s1[], char s2[]) {
   return s1 == s2;
}

As far as I know this compares only the addresses of the first elements from char array s1 and char array s2.

But strange is if I compare (in Visual Studio) two equal char arrays like

 comp("test","test");

I got 1 (true) instead of 0 (false). But should the addresses not be different and therefore the result should be always 0?

like image 833
knowledge Avatar asked Dec 02 '25 23:12

knowledge


1 Answers

I'd say this is the result of a compiler optimisation using the same instance of the string. If you did something like this you'd prove == doesn't work as you suggest:

char s1[10];
char s2[10];
strcpy(s1, "test");
strcpy(s2, "test");
printf("%d\n", comp(s1, s2));
like image 65
John3136 Avatar answered Dec 04 '25 12:12

John3136