C confusion about pointers and arrays
char a[]="HELLO";
char *p="HELLO";
will a[2]
and p[2]
fetch the same charact开发者_如何学编程er?
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.
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.
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.
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 ;)
Both will have the same character value.
精彩评论