我有以下代碼:
#include <stdio.h>
int main(void)
{
int a[10]={10,20,30,40,50,60,70,80,90,100};
int *p;
p=a;
int **d=&p;
printf("Address stored in p:%d\n",p);
printf("Pointer p's address:%d\n",d);
printf("Pointer d's content:%d\n",*d);
printf("Pointed array content:%d\n",(*d)[9]);
printf("Unexpected:\n");
for (int i = 0; i < 10; i)
{
printf("%d\n",d[i]);
}
printf("Expected:\n");
for (int i = 0; i < 10; i)
{
printf("%d\n",(*d)[i]);
}
}
我意識到第一個回圈是取消參考指向指標的指標的不正確方法。執行后,雖然我得到以下輸出:
6487520
10
30
50
70
90
2
6487512
1
7607184
第一次迭代顯示了 a[0] 的地址,但為什么我得到的陣列內容帶有奇數索引?這種行為是隨機的(取決于編譯器)并且理解它毫無意義嗎?
uj5u.com熱心網友回復:
我們無法知道它為什么會產生這些數字。一般的答案是從未知指標讀取值是未定義的行為。我們無法知道它可能回傳什么,或者即使回傳的值在程式運行之間是否一致。該程式甚至可能崩潰或產生奇怪的行為。
更實際的答案是我們知道它d在堆疊中,所以我們觀察到的值可能也是堆疊的一部分。d是一個指標而不是一個整數,所以它可能有不同的大小。由于我們看到每隔一個值,這可能意味著您的指標是系統上的大小的兩倍int。
您可以通過添加以下內容來測驗該理論:
for (int i = 0; i < 10; i) {
printf("Reading int (%d bytes) %ld bytes from the start of d: %d\n",
sizeof(int),
(long) (d i) - (long) d,
d[i]
);
}
當我在我的系統上運行它時,我得到:
Reading int (4 bytes) 0 bytes from the start of d: -601183712
Reading int (4 bytes) 8 bytes from the start of d: -601183728
Reading int (4 bytes) 16 bytes from the start of d: 10
Reading int (4 bytes) 24 bytes from the start of d: 30
Reading int (4 bytes) 32 bytes from the start of d: 50
Reading int (4 bytes) 40 bytes from the start of d: 70
Reading int (4 bytes) 48 bytes from the start of d: 90
Reading int (4 bytes) 56 bytes from the start of d: -2024523264
Reading int (4 bytes) 64 bytes from the start of d: 0
Reading int (4 bytes) 72 bytes from the start of d: 2048278707
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/496566.html
下一篇:從C中的字串中洗掉最常見的單詞
