Here
char t1[] = "abc";
t1
is character array and its name itself address i.e t1
and string literal "abc"
both have same base address & both resides in stack section of RAM. It looks like
0x100 0x101 0x102 0x103 <-- lets assume base address of t1 is 0x100
------------------------
| a | b | c | \0 |
------------------------
0x100
|
t1
And here
char *t2 = "abc";
t2
is a character pointer, its itself resides in stack section but it points to string literal "abc"
which presents in code section(read only) of RAM. It looks like
0x300 0x301 0x302 0x303 <-- lets assume string literal "abc" stored at 0x300 location
------------------------
| a | b | c | \0 |
------------------------
---------
| 0x300 | ---> t2 points to different memory location
---------
0x200 ---> memory address allocated for t2
|
t2
Now when you do
if (t1 == t2) { } /* 0x100 == 0x300 --> false */
you are comparing two addresses i.e 0x100
and 0x300
(in real time operating system assigns some real address not like 0x100
) which is not same, hence the result "different"
.
But both location contents are same, so you should be using strcmp()
to compare them. For e.g
if (strcmp(t1, t2) == 0) { }
However, if t1
and t2
are of same char*
type. For e.g
char *t1 = "abc";
char *t2 = "abc";
in that case the both t1
and t2
points to same string literal & compiler will not be storing string literal "abc"
to two different locations. Hence when you do
if(t1 == t2) { }
it results in same as t1
and t2
both points to same memory location.