Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing character arrays with an == operator in C

I know that the correct way to compare "strings" in C is by using strcmp, but now I tried comparing some character arrays with the == operator, and got some strange results.

Take a look at the following code:

int main()
{
    char *s1 = "Andreas";
    char *s2 = "Andreas";

    char s3[] = "Andreas";
    char s4[] = "Andreas";

    char *s5 = "Hello";

    printf("%d\n", s1 == s2); //1
    printf("%d\n", s3 == s4); //0
    printf("%d\n", s1 == s5); //0
}

The first printf correctly prints a 1, which signals that they are not equal. But can someone explain to me why, when comparing the character arrays, the == is returning a 0 ?

Can someone please explain to me why the first printf is returning a 1 (ie, they are equal) and the character arrays are returning a 0 ?

like image 824
Andreas Grech Avatar asked Nov 28 '22 12:11

Andreas Grech


1 Answers

The == is comparing the memory address.
It's likely that your compiler is making s1 and s2 point to the same static data to save space.

ie. The "Andreas" in the first two lines of code is stored in your executable data. The C standard says these strings are constant and so has optomized the two pointers to point to the same storage.

The char[] lines create a variable by copying the data into the variable and so are stored at different address on the stack during execution.

like image 181
Martin Beckett Avatar answered Jan 11 '23 20:01

Martin Beckett