从int *到int的转换无效

时间:2014-08-29 14:53:18

标签: c++

我自学指针,想知道传递地址的正确方法是什么?

    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;

    }

我在“gana =&amp; tiu;”上收到错误&GT; int *转换为int [f-permissive]无效。

3 个答案:

答案 0 :(得分:1)

您将变量gana定义为类型int

    int kevin = 10,tiu,gana;

但您尝试将int *类型的对象分配给它

gana = &tiu;

如果要将变量定义为类型int *

    int kevin = 10,tiu, *gana;

然后这句话

    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;

答案 1 :(得分: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;

答案 2 :(得分:0)

指针不是整数。他们不兼容。

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

gana = (int)&tiu;

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