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

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
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ā€‹.
20th Oct 2018, 8:01 AM
Jared Bird
Jared Bird - avatar