2012-08-31 69 views
-2

好吧我理解指針指針的概念。但我不知道爲什麼這不起作用。指針指針(C++)

void function(int **x) 
{ 
    *x = 10; 
} 

我不斷收到錯誤: 類型「INT」的值不能分配給類型的實體爲「int *」

什麼我做錯了或什麼我不理解指點一下指針?

omg x_x我把C和C++混淆了。

+14

當你說'我明白指針pointers'的概念,究竟是什麼意思呢? –

+3

它需要是'** x = 10;'。 –

+3

你爲什麼試圖給一個指針賦值'10'?記憶中的第十個地址是如此迷人? –

回答

10

x是一個指向指針的指針,因此您必須對其進行兩次取消引用以獲取實際對象。例如。 **x = 10;

0

x指向一種int *而不是int。你要麼做static int i = 10; *x = &i**x = 10

+6

你不能拿這樣的常數的地址。 –

+2

當然不是'&10'。常量沒有地址。 –

+0

@ RichardJ.RossIII,在這種情況下,你是對的,但如果它是'const int'就沒關係。 –

7

Ok I understand the concept of pointers to pointers.

不想...

*xint*,所以你不能分配int它。

指針指針的概念來自C,其中引用不可用。它允許引用語義 - 即你可以改變原來的指針。

+2

你可以給指針賦一個'int',整數可以轉換成指針。 99.999%的時間,當然不應該。 –

+0

是的,我正在研究互聯網上的指針指針,並遇到一些C例子。我認爲它們是可以互換的。 – user1583115

+0

@DanielFischer是隱式的演員嗎? (那就是我的意思)。和AFAIK,你可以分配任何東西:) –

6

總之,您需要解除引用兩次。 取消引用返回一個指針龐廷的事情,所以:

int n  = 10; //here's an int called n 
int* pInt = &n; //pInt points to n (an int) 
int** ppInt = &pInt //ppInt points to pInt (a pointer) 

cout << ppInt;  //the memory address of the pointer pInt (since ppInt is pointing to it) 
cout << *ppInt;  //the content of what ppInt is pointing to (another memory address, since ppInt is pointing to another pointer 
cout << *pInt;  //the content of what pInt is pointing to (10) 
cout << **ppInt; //the content of what the content of ppInt is pointing to (10)