After a long break,I am back to C but getting confused even on some simple issues.
So one is here.
Here is the simple code :
#include<stdio.h>
int main() {
char str1[]="hello";
char str2[]="hello";
if(str1==str2)
printf("equal");
else
printf("unequal");
}
Output:
unequal
but when I tried this one ,it worked
char *str1="hello";
char *str2="hello";
Output
equal
Please if anyone can provide a detailed explanation for it.
Can someone tell me what exactly does C99 standard say about the situation ???
When you do
==with pointers (which is whatstr1andstr2are in both cases1) all you are doing is comparing the two addresses to see if they are the same. When you doYou are creating two arrays on the stack that hold
"hello". They are certainly at different memory locations, sostr1 == str2isfalse. This is likeWhen you do
You are creating two pointers to the global data
"hello". The compiler, seeing that these string literals are the same and cannot be modified, will make the pointers point to the same address in memory, andstr1 == str2istrue.To compare the content of two
char*s, usestrcmp:This is roughly the equivalent of
1 In the
char*version, this is true. In thechar[]version,str1andstr2are really arrays, not pointers, however when used instr1 == str2, they decay to pointers to the first elements of the arrays, so they are the equivalent of pointers in that scenario.