Search code examples
c++cstring-literals

Comparing Char Pointers


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
=
  1. How come the two pointers are of different addresses and the operation == returns true?

  2. Why didn't the compiler store the string literal Hesham just once and use its address twice for x and y?


Solution

  • 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 for x and y?

    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.