G
Giannis Papadopoulos
Andrey said:CBFalconer said:Why is there a difference when we compare
char str1[]="Hello";
char str2[]="Hello";
with strcmp and ==
strcmp gives them as equal and == gives them as unequal
The == operator compares the arrays addresses (obvioulsy different,
because str1 and str2 are different objects) while the strcmp()
function compares the string char by char. Big difference.
They may not be different objects.
They definitely are in this case. Note that the OP did not compare
the string literals, but named objects.
You are wrong. Why did you snip my explanation of why this is so,
which I have appended below.
They may not be different objects. The system is allowed to merge
identical string constants. The result of those test would tell
whether is has done so. This is one fundamental reason for those
constants not to be writeable.
...
The "system " is indeed allowed to merge identical string literals. But that's
all that it is allowed to do: merge the anonymous string literal objects. This
means that the first "Hello" literal might have that same address as the second
"Hello" literal. However, this has absolutely noting to do with objects 'str1'
and 'str2'. These two are distinct array objects. They are not string literals.
They are distinct from each other, they are distinct form the anonymous string
literal objects. The implementation is not allowed to "merge" 'str1' and 'str2'.
'str1' and 'str2' are always guaranteed to have different addresses in storage,
meaning that the above '==' operator is guaranteed to evaluate to 0.
A different example might look as follows
const char* str1 = "Hello";
const char* str2 = "Hello";
In this case the pointers are initialized with the addresses of the actual
anonymous string literal objects. And in this case, if the literals get merged,
the pointers will indeed compare equal. But not in the original example.
I think you should first read, then respond...
--
one's freedom stops where other's begin
Giannis Papadopoulos
http://dop.users.uth.gr/
University of Thessaly
Computer & Communications Engineering dept.