c++ 之warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int*’

#include
#include

class Base
{
    public:
        int x;
        int y;
};

int main(int argc, char ** argv)
{
    Base base;

    printf("base address is 0x%x.\n", &base);
}

编译报警告.
报:warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘Base*’ [-Wformat=]

修改为:
printf("base address is 0x%x.\n", (int *)&base);
报: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int*’ [-Wformat=]


修改为:
printf("base address is 0x%x.\n", (unsigned int)(int *)&base);
报: error: cast from ‘int*’ to ‘unsigned int’ loses precision [-fpermissive]

修改为:
printf("base address is 0x%x.\n", (unsigned int *)&base);
报: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘unsigned int*’ [-Wformat=]

修改为:
printf("base address is 0x%x.\n", (long)(int*)&base);
报: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘long int’ [-Wformat=]

因此再修改为:
printf("base address is 0x%x.\n", (unsigned int)(long)&base);
编译警告消除。

先转换成long,再转换成unsigned int。正确的修改为:
printf("base address is 0x%x.\n", (unsigned int)(long)&base);

你可能感兴趣的:(C/C++,c++)