Reputation: 161
char a[]="HELLO";
char *p="HELLO";
will a[2]
and p[2]
fetch the same character?
Upvotes: 0
Views: 195
Reputation: 44804
In both cases they will fetch an 'L'
. However, it isn't the same 'L'
. They are stored in different places. That means if you compare their pointers, they will not be equal.
Upvotes: 2
Reputation: 45104
Yes.
p[2] is equivalent to *(p+2)
HELLO
^
*(p+2)
Should be noted, that the first "HELLO" will probably be stored in a writable memory page, while the second "HELLO" will probably be stored in a read only page. This is very closely related to the compiler / platform you are on.
Upvotes: 2
Reputation: 55726
I guess it depends on the compiler you use, but the answer is probably no.
By the way, you can test this easily by comparing the addresses of the two characters. If they differ, then: no.
Anyway, you shouldn't rely on this ;)
Upvotes: 0
Reputation: 24502
What they will fetch is a char-sized chunk of memory located 2 char-sized steps (2 bytes here) after the beginning of each, or after the address in memory to which each var points. This happens to be 'L' i the example, but this is not the same address in memory.
So yes, in the example given, they will fetch the same character.
Upvotes: 3