1

as I understand in C , char *x is equal to the address of the first char in string x. in the below code example when I run the program in debugger , the value of l and m is always the same address and the conditional statement is true :

int main(void)
{

    char *l = "hello";

    char *m = "hello";

    if (l == m)
        printf("true");
}

i don't understand why the two variables always have the same value (address)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Ahmed Sh
  • 31
  • 3

2 Answers2

3

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

So the compiler may store identical string literals either as one string literal or as separate string literals. Usually compilers provide an option that allows the user to select how string literals will be stored.

It seems that the compiler you are using stores identical string literals as one string literal by default. You may imagine the situation the following way

char string_literal_hello[] = { 'h', 'e', 'l', 'l', 'o', '\0' };

int main(void)
{

    char *l = string_literal_hello;

    char *m = string_literal_hello;

    if (l == m)
        printf("true");
}

Thus the both pointers l and m point to the same character 'h' of the character array string_literal_hello that the compiler stores in a string literal pool.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Pedantically, `char string_literal_hello[] = "hello";` isn't a string literal. ;-) – Andrew Henle Oct 13 '20 at 10:24
  • @AndrewHenle String literals are character arrays. – Vlad from Moscow Oct 13 '20 at 10:26
  • True, but your example is an example of a character array that's initialized to hold the value of the "hello"` string literal. If your system puts string literals into read-only memory, you couldn't modify an actual string literal but you could modify your `string_literal_hello` array because it's not actually a string literal. Per [the definition of a string literal](https://port70.net/~nsz/c/c11/n1570.html#6.4.5p3): *A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz".* That's not your `string_literal_hello`. – Andrew Henle Oct 13 '20 at 12:12
  • As I said, "pedantically". ;-) – Andrew Henle Oct 13 '20 at 12:12
1

You are comparing the address values in l and m and with constants like this the compiler chose the same address as the values are the same.

Change it into this and 'l' and 'm' will contain different addresses and tru is not printed.

char l[] = "hello";

char m[] = "hello";
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98