开发者

Printf(" ABCD" ); printf("ABCD" +1);

开发者 https://www.devze.com 2023-03-15 20:31 出处:网络
void main() { printf(\"ABCD\");开发者_StackOverflow printf(\"\\n\"); printf(\"ABCD\" +1); printf(\"\\n\");
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";

Printf(" ABCD" ); printf("ABCD" +1);


"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.

0

精彩评论

暂无评论...
验证码 换一张
取 消