[英]C++ Pointer to Pointer
我想要一個指向常量的指針,並將它的地址傳遞給 function 它將增加它。
int f1(const int **ptr) {
int n = **ptr; //use pointer
(*ptr)++; //increment pointer
return n;
}
void foo(const int *data) {
const int *p = data;
const int n = f1(&p); //error: invalid conversion from ‘const int**’ to ‘int**’
//error: initializing argument 1 of ‘int LevelLoader::readWord(byte**)’
}
如何聲明指針?
嘗試
int f1(const int *& ptr) {
int n = *ptr;
++ptr;
return n;
}
void foo(const int *data) {
const int *p = data;
const int n = f1(p);
}
反而。
錯誤消息表明LevelLoader::readWord
不采用const byte**
。
這個:
const int *data;
是一個指向常量integer 的指針。 這意味着您不允許更改 data 指向的data
。 您可以讀取和復制數據,但不能:
(*data) = 5;
這在 C++ 中是非法的,因為它被聲明為const int *
。
如果你獲取一個const int *
的地址,你會得到一個const int **
,它是一個指向常量integer 的指針的指針。 所以你仍然不能改變 integer。 任何這樣做的嘗試都會導致編譯器抱怨。
如果您希望能夠更改 integer,則foo
和f1
不應采用const int *
值。 他們應該采用int *
值。
我不想修改常量。 我想修改指向它的指針(foo()中的p)
所以,你得到了一個指針。 你想增加指針。 所以就這樣做:
void foo(const int *data) {
const int *p = data;
data++;
}
您已經增加了指針。 這不會影響foo
的調用者,因為指針本身是按值復制的。
再次檢查,這段代碼是正確的。 它不應該產生您聲稱的錯誤。
編輯:您解決了無效問題,因此相應地修改了答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.