2012-08-31 287 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)