Member Avatar for SoreComet

Can string be compared with == operator? I know that they can be compared using strcmp() function. But this snippet confused me a lot

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char str1[]="Good Morning";
    char str2[]="Good Morning";
    if(str1 == str2)
        printf("Equal");
    else
        printf("Not Equal");
    return 0;
}

The output of this program in "Not Equal". Can anyone please explain the output

Recommended Answers

All 3 Replies

== for character array (char*, actually) compares the pointers themselves. If the two pointers are not pointing at the exact same memory location the results will be false.

If you want to compare the strings themselves (the individual character-by-character comparison) you will want to use something like strcmp.

str1 is effectively a pointer. A pointer is a memory address. In this case, it's the memory address of the first char in the array of char created on line 5.

str2 is effectively a pointer. A pointer is a memory address. In this case, it's the memory address of the first char in the array of char created on line 6.

Are these two memory addresses the same? No, because those two char arrays occupy different places in memory.

So this
str1 == str2
is comparing two memory addresses, which are not the same, and thus comes back as false.

Is that clear, or shall I explain further?

Member Avatar for SoreComet

Also on strcmp() the result will be 0 obviously if the contents of the array are same. Thanks @moschops and l7sqr for your answers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.