-4

Ok so here we are comparing the memory location of the pointer to the string literal name[10] or Michael (or something like that)

char name[10]="michael";
char name2[10]="michael";

if (name == name2) { printf("ok\n");
    printf("OKAF\n");
}

And of course if will evaluate to false and nothing happens, however:


    char* name="michael";
    char* name2="michael";

    if (name == name2) { printf("ok\n");
            printf("OKAF\n");
        }


    }
~                       

3rd example: (this one works as well)

 char name="michael";
    char name2="michael";

    if (name == name2) { printf("ok\n");
            printf("OKAF\n");
        }

Here we are also comparing the memory location except in this case it evaluates to true?

My question is and I apologize in advance for my vapidity I'm a little confused as to why one works over the other; I have also seen implementations comparing two strings without using strcmp or the likes. What am I missing here can someone explain this to me in a language perhaps I can understand?

I've tried all 3 of those and 2 of the 3 of them evaluate to true as expected but I am still really confused as to why == with the IF statement in C is suppose to compare memory locations why using pointers or poorly initialized and defined chars work if its only suppose to compare memory locations.

wohlstad
  • 12,661
  • 10
  • 26
  • 39

1 Answers1

2

First example: You are allocating two arrays pointing at two different locations in code. Result: The pointers are not equal.

Second: You have two distinct pointers that point to the same string. The compiler MAY optimize these two strings, since they are actually the same, to be stored in the same region of the text part of your program, resulting in the comparison to be successful.

Third: You are not comparing memory locations, you are comparing characters, which just happen to be the same. However you should be getting a warning that you are assigning a const char * to a char.

Refugnic Eternium
  • 4,089
  • 1
  • 15
  • 24