I'm trying to compare two char pointers:
char * x;
char * y;
x = "Hesham";
y = "Hesham";
printf("%d %d \n", &x, &y);
if(x==y)
{
printf("=\n");
}
else
{
printf("!=\n");
}
The execution result is:
2293368 2293360
=
How come the two pointers are of different addresses and the operation ==
returns true?
Why didn't the compiler store the string literal Hesham
just once and use its address twice for x
and y
?
How come the two pointers are of different addresses and the operation
==
returns true?
&x
and &y
are the addresses of the pointer variables rather than the addresses of the string. Since x
and y
are different variables, they have different addresses.
You then compare the values of x
and y
which happen to be the same because the compiler has noticed that the two string literals have the same value and only stored a single copy of the literal.
Why didn't the compiler store the string literal
"Hesham"
just once and use its address twice forx
andy
?
It did. That's why x == y
evaluates as true.
One other point to make is that you should use the %p
format specifier when printing pointers.