簡體   English   中英

理解指針指針的概念

[英]Understanding pointer to pointer concept

我是C的初學者,我試圖理解指針指針的概念。 我有以下示例

int main() {
char *names[]={"Peter", "Dan"};
printf("names = %p\n", names);
printf("(char *)names = %p\n", (char *)names);
printf("(char **)names = %p\n", (char **)names);
printf("*(char *)names = %p\n", *(char *)names);
printf("*(char **)names = %p\n", *(char **)names);
return 0;
}

Output:
names = 0x7fff167f7c00
(char *)names = 0x7fff167f7c00
(char **)names = 0x7fff167f7c00
*(char *)names = 0x58
*(char **)names = 0x400658

這里我的問題為什么*(char *)名稱不會返回0x400658? 從上面的輸出我可以看到(char *)名稱的值是0x7fff167f7c00,現在,如果我取消引用它,它應該顯示我0x400658對嗎?

有人可以解釋一下這是如何工作的嗎?

初步問題后編輯:

我做了一些進一步的分析並找出了一些理論,但仍需要幫助才能理解。 在執行(char *)名稱時,它認為它是指向char的指針因此*(char *)名稱打印0x400658的地址的1字節,即0x58。 但在(char **)名稱的情況下,它認為作為指針的指針,當解除引用時,它給出整個地址ie0x400658。 下面將幫助像我這樣的新手更多地了解這一點

printf("notes =%p\n", notes);
printf("(char *)notes+1 =%p\n", ((char *)notes+1));
printf("(char **)notes+1 =%p\n", ((char **)notes+1));

Output:
notes =0x7fff75e4c260
(char *)notes+1 =0x7fff75e4c261
(char **)notes+1 =0x7fff75e4c268

以上是我的理論,但現在讓我說我觀察到的是正確的,但有時我會低於輸出

*(char **)notes =0x4007ec
*(char *)notes =0xffffffec 

考慮到我的理論是正確的,這應該是0xec? 為什么它附加了ffff? 我錯過了什么嗎?

以下是我的閱讀方式:

// (char*) is an address (of char): 8 bytes
(char *)  names = 0x7fff167f7c00 // actual address of names

// (char**) is an address (of char*): 8 bytes
(char **) names = 0x7fff167f7c00 // actual address of names.

// *(char*) is a char: 1 byte.
*(char *) names = 0x58           // first byte of the first value of names (ie address of "Peter").

// *(char **) is an address (of char): 8 bytes
*(char **)names = 0x400658       // first value of names (ie address of "Peter").

關於0xec

此代碼: printf("*(char *)names = %p\\n", *(char *)names); 打印指針(因為%p ),給定的值是*(char *)char

發生的事情是給定的char(1個字節)在打印之前被轉換為指針(8個字節)。

此轉換旨在失敗。 您不能擁有來自單個數據位的有效指針。

對於0x58 ,因為char是88而88是8字節整數是0x00..0058它被打印為0x58

Char是簽名類型。 0xec ,因為char是-20,而作為4字節有符號整數的-20是0xffffffec ,符號字節填充所有新位。 這稱為符號傳播

所以你可以看到0xec被轉換為0x00000000ffffffec 為什么符號傳播僅發生在前4個字節上可能有多種解釋。 我看到的第一個是性能。

無論如何,char到指針的轉換將取決於編譯器,目標等......並且因為結果是無法使用的,所以它可以是任何東西。

names變量的類型是指向char的指針。 通過使用表達式*(char *)名稱,您假設名稱是指向char的指針並取消引用它,即*(char *)名稱表達式的類型為char。

您通過將char **對象類型轉換為char *對象來引入錯誤。 因此,你不能指望在兩種情況下得到相同的答案。

暫無
暫無

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

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