2014-08-29 86 views
-3

我是自学指针,想知道传递地址的正确方法是什么?从int *到int的转换无效

int main(){ 
     int kevin = 10,tiu,gana; 

     int *kevinpointer; 
     kevinpointer = &kevin; 

     tiu = kevin; 
     gana = &tiu; 

     cout << "The value of Kevin is: "; 
     cout << kevin << endl; 

     cout << "The address of Kevin is: "; 
     cout << kevinpointer << endl; 

     cout << "The address of KevinPointer is: "; 
     cout << *kevinpointer << endl; 

     cout << "The value/address of tiu is: "; 
     cout << tiu << endl; 

     cout<< "The address of gana is: "; 
     cout << gana << endl; 

    } 

我得到一个错误的 “加纳= &tiu;”> INT *的转换无效为int [F-许可。

+1

在你的代码片段中,'gana'是一个'int',而不是指向'int'的指针,因此你不能在不触发警告的情况下为它分配一个地址'&tiu'。 – 2014-08-29 14:55:32

+0

感谢您的回应!非常感激。 – 2014-08-29 14:56:30

回答

1

您定义的变量gana具有类型int

int kevin = 10,tiu,gana; 

,但你想int *类型的对象赋给它

gana = &tiu; 

如果您想将变量定义为有型int *

int kevin = 10,tiu, *gana; 

then this statement

gana = &tiu; 

会是正确的。

要考虑到这些语句

cout << "The address of KevinPointer is: "; 
cout << *kevinpointer << endl; 

//... 

cout<< "The address of gana is: "; 
cout << gana << endl; 

是错误的。应该有

cout << "The address of KevinPointer is: "; 
cout << &kevinpointer << endl; 

//... 

cout<< "The address of gana is: "; 
cout << &gana << endl; 
+0

感谢您的帮助! :D – 2014-08-29 14:57:45

0

ganaint,而你试图使用它作为一个int*。将前两行改为:

int kevin = 10, tiu; 
int *kevinpointer, *gana; 

程序应该编译。然而,你有这个片段:

cout<< "The address of gana is: "; 
cout << gana << endl; 

这没有任何意义。变量gana不能保存自己的地址。这将要求它同时是int*int**,这没有任何意义。此代码应该是:

cout << "The address of tiu is: " << gana << endl; 
+0

感谢您的回复! :) – 2014-08-29 14:58:05

+0

@Josh:哦,真的吗?和'cout <<“gana的地址是:”<< gana;'会打印出'gana'的地址? – 2014-08-29 14:58:41

+0

@PiotrS。通过*一切应该工作*我的意思是编译和运行。虽然好,但我会编辑我的答案。 – scohe001 2014-08-29 14:59:38

0

指针整数。它们不兼容。

为了强制从指针获取整数,请使用显式转换。

gana = (int)&tiu; 

此外,标准不说sizeof(int) == sizeof(void *)。如果要使用大小等于指针的整数类型,则应使用intptr_tuintptr_t,它位于<stdint.h>中。

+0

你绝对不应该使用C风格的演员。 – 2014-08-29 15:31:10

+0

@ChristianHackl那么,从OP的代码判断,他可能实际上想要使用C> o < – ikh 2014-08-29 23:23:48

+0

这个问题被标记为C++。 – 2014-08-30 07:34:00