簡體   English   中英

了解指向 c 中指針的指針

[英]Understanding pointer to pointers in c

我有以下代碼:

#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] 的地址,但為什么我得到的數組內容帶有奇數索引? 這種行為是隨機的(取決於編譯器)並且理解它毫無意義嗎?

我們無法知道它為什么會產生這些數字。 一般的答案是從未知指針讀取值是未定義的行為。 我們無法知道它可能返回什么,或者即使返回的值在程序運行之間是否一致。 該程序甚至可能崩潰或產生奇怪的行為。

更實際的答案是我們知道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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM