String Comparison in C | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson

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"); } }

20th Oct 2018, 7:32 AM
Kunal Chand
Kunal Chand - avatar
2 Answers
+ 2
strcmp is a better way to compare strings.
20th Oct 2018, 7:50 AM
Микола Федосєєв
Микола Федосєєв - avatar
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​.
20th Oct 2018, 8:01 AM
Jared Bird
Jared Bird - avatar