When you do == with pointers (which means str1 and str2 in both cases 1 ), all you do is compare the two addresses to see if they are the same. When you do
char str1[]="hello"; char str2[]="hello";
You create two arrays on the stack that contain "hello" . They, of course, are in different places of memory therefore str1 == str2 - false . It looks like
char str1[6]; str1[0] = 'h'; str1[1] = 'e'; str1[2] = 'l'; str1[3] = 'l'; str1[4] = 'o'; str1[5] = '\0';
When you do
char *str1="hello"; char *str2="hello";
You create two pointers to the global "hello" data. The compiler, seeing that these string literals are the same and cannot be changed, will force the pointers to indicate the same address in memory, and str1 == str2 - true .
To compare the contents of two char* s, use strcmp :
// strcmp returns 0 if the two strings are equal if (strcmp(str1, str2) == 0) printf("Equal"); else printf("Not equal");
This is roughly equivalent
char *a, *b;
1 In the
char* version, this is true. In the
char[] version,
str1 and
str2 are arrays, not pointers, but when used in
str1 == str2 they break up into pointers to the first elements of the arrays, so they are equivalent to pointers in this scenario.
source share