2

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
knowledge
  • 941
  • 1
  • 11
  • 26

4 Answers4

7

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));
John3136
  • 28,809
  • 4
  • 51
  • 69
4

It is so because same strings are stored as one string in the string pool during compilation . Therefore both points to the same address as there is only one "test" string in the string pool. Memory heap

Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29
3

String literals are often reused by optimizing compilers, so if you use the same string literals twice, both will be the exactly same string literals. And your function are comparing pointers, and as both string literals are the same then you are comparing the same pointers which of course will give you a "true" value.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Read about the concept of mutabe and immutable string. String stored in stack when compared returns true but if one string in heap an other in stack it returns false.

Second question is, are you using prpredefined functions to compare 2 string then the functions works as follows

Compare(s1,s2) returns positive zero or negative according as s1 preced, equals or follows s2 in lexicographical ordering basednon unicide character.

Regards.

CocoCrisp
  • 807
  • 1
  • 9
  • 26