{
char *x = "abc";
int * y = &x;
printf("%s", *(*y));
return 0;
}
那行不通,我很難弄清楚為什么
通常,我只是嘗試通過指向指標的指標來訪問字串,但我不知道如何
謝謝!
uj5u.com熱心網友回復:
為什么它不起作用?
int *y是一個指向 int 的指標(不是指向指標的指標),*y是int. 整數值不是指標,因此不能取消參考 - 因此編譯器錯誤。我從字串別名規則中抽象出來。您需要記住不要使用其他指標型別取消參考指標。它是 C 中的 UB。
int main(void){
char *x = "abc";
char **y = &x; // pointer to pointer to char
printf("`%s`\n", *y); // single derefence gives pointer to char
printf("'%c'\n", **y); // double dereference gives char
return 0;
}
https://www.godbolt.org/z/aoEz57o5d
uj5u.com熱心網友回復:
指標存盤記憶體地址。如果您已經宣告了一個變數和一個指向該變數的指標,則該指標將存盤它所指向的變數的地址。下面是一個帶有注釋的示例。
int a = 1; // allocated at 0x100, content is 1.
int* ptrA = &a; // allocated at 0x200, content is 0x100 (address of 'a')
為了通過指標訪問 'a' 的內容,您必須取消參考它,這是使用取消參考運算子 (*) 完成的。
printf("'a' content is %d", *ptrA);
指向某個指標的指標還存盤了一個記憶體地址,但在這種情況下,是另一個指標的記憶體地址。如果你已經宣告了一個變數、一個指向該變數的指標和一個指向該變數指標的指標,第一個指標仍然像第一個例子一樣存盤變數的地址,最后一個指標存盤第一個指標的地址。下面是一個帶有注釋的示例。
int a = 1; // allocated at 0x100, content is 1.
int* ptrA = &a; // allocated at 0x200, content is 0x100 (address of 'a')
int** ptrToPtrA = &ptrA; // allocated at 0x300, content is 0x200 (address of 'ptrA')
為了通過指向指標的指標訪問 'a' 的內容,您必須取消參考它,一次是為了檢索指向指標 'ptrToPtrA'(指標 'ptrA')的指標的內容,從這里開始,一次是為了檢索指標'ptrA'的內容(變數內容'1')。
printf("'a' content is %d", **ptrToPtrA);
下面是帶有評論的最后一個示例,更接近您的原始問題。
#include <stdio.h>
int main(void)
{
// pointer to char (stores the address of a char)
char* x = "abc";
printf("'x' address is #%p, content is %c\n", x, *x);
// pointer to pointer to char (stores the addres of a pointer to char)
char** xPtr = &x;
printf("'xPtr' address is #%p, content is %p\n", xPtr, *xPtr);
printf("'x' content through 'xPtr' is %c\n", **xPtr);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362491.html
下一篇:在c中轉換通用指標
