[英]What the following code prints / with arrays, pointers etc
我在解決這個問題時遇到了問題,所以如果有人有類似的問題,它會對我有很大幫助。
short y[2][3]={{0123},{0x12345}},*p=y[1];
printf("01:%x\n", y);
printf("02:%x\n", p);
printf("03:%x\n", sizeof(y));
printf("04:%x\n", sizeof(y[0]));
printf("05:%x\n", sizeof(&y[0]));
printf("06:%x\n", sizeof(*p));
printf("07:%x\n", sizeof(p++));
printf("08:%x\n", *p++);
printf("09:%x\n", *p);
return 0;
誰能給我解釋一下為什么打印輸出是這樣的?
01:61ff10
02:61ff16
03:c
04:6
05:4
06:2
07:4
08:2345
09:0
我的想法:
01:Prints the address where the array y begins.
02:Prints the address of the pointer, which points to the second element of the array. Since we have 2 * 3 elements that are of type short, each subsequent element of the zero element will increase by 6.
03:Since we have 2 * 3 elements, which is equal to 6, but the elements of the type are short, so it will print hexadecimal c
04:the number of elements in the zero position is 3, but they are of the short type, so it prints 6
05:prints the sizeof addresses of the first element of the array which is 4
06:I don't know why it prints 2 here
07:Prints the sizeof of the pointer address which is 4, it will increase after printing
08:I do not understand
09:I do not understand
誰能解釋為什么它打印成這樣?
好吧,讓我們來看看:
y
的地址。p
的值,它包含y[1]
的地址,它是short[3]
類型的第二個元素。 在您的系統上, short
的大小顯然是 2,因此 #01 的偏移量是 6。y
的大小, 2 * 3 * sizeof (short)
給出 12,十六進制c
。y[0]
的大小,類型為short[3]
。 6,如你所見。y[0]
的地址大小,顯然地址的大小在您的系統上是 4。p
指向的object的大小。 這是一個short
的,所以 2。p++
的大小,它是一個地址,所以是 4。不, p
沒有遞增,因為表達式沒有被計算。p
指向的object的值,即y[1][0]
。 由於0x12345
的初始值是一個太大而無法存儲在short
中的int
,因此它被截斷為0x2345
。 讀取值后, p
遞增。p
指向的元素,即y[1][1]
。 它被初始化為 0。筆記:
你應該從你的編譯器那里得到警告:
%p
。sizeof
結果的類型可能與格式%x
不匹配。你應該認真對待警告,它們總是暗示你很可能犯了錯誤。
N6) Sizeof(*p) 是 p 指向的數據類型的大小。 p 是指向 short 的指針:所以 2 個字節。
N8) p 是指向 short 的指針,它指向數組元素 y[1][0]。 y[1] 和 y[1][0] 具有相同的 memory 地址。
所有數組元素都很短,0x12345 在數組初始化時截斷為 0x2345。 所以 output 是 2345。此外,p++ 增加指針值以指向下一個短 y[1][1]。
N9) 由於步驟 N8 中的 p++,指針現在指向 y[1][1],它被初始化為 0(默認情況下,因為未提供初始值)- output 為 0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.