void main()
{
printf("ABCD");开发者_StackOverflow
printf("\n");
printf("ABCD" +1);
printf("\n");
printf("ABCD" +3);
}
Outputs is:
ABCD
BCD
D
Can anyone explain me why?
"ABCD" is actually an array of characters {'A','B','C','D', '\0'} (where '\0' is the trailing null byte). If you add 3 to that, then that is the equivalent of advancing a pointer 3 bytes forward from A, so you end up pointing at D.
Question 6.2 in the C FAQ has a picture that makes this clearer. The array decays to a pointer as described in 6.4 so you have the situation of the variable p.
char a[] = "hello";
char *p = "world";

"ABCD" is treated as a pointer to a block of memory containing four characters followed by a null terminator (\0).
"ABCD" + 1 adds 1 to the pointer, causing it to point one byte further.
加载中,请稍侯......
精彩评论