0
String Comparison in C
Why the hell the following code gives output as : "Different Same" . CODE : #include<stdio.h> int main() { char ch[] = "Hello"; char ptr[] = "Hello"; if(ch == ptr) { printf(" Same\n"); } else { printf(" Different\n"); } char * fool = "World"; char * hop = "World"; if(fool == hop) { printf(" Same"); } else { printf(" Different"); } }
2 odpowiedzi
+ 2
strcmp is a better way to compare strings.
0
You are comparing the address of the string not the string. The first will always give different as they are stored in different arrays. The second is a pointer to a string in static memory. The two pointers may or may not point to the same address, it depends on the compiler.
Use strcmp() when comparing c strings.