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

Edited 2 Years Ago by Ladis

== 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?

Edited 2 Years Ago by Moschops

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

This question has already been answered. Start a new discussion instead.