c++ - 保存变量的地址
高洛峰
高洛峰 2017-04-17 14:30:00
0
2
711
#include <cstdio>
int main(int argc, char const *argv[])
{
    int aa[10]={1,2,3,4};
    int * a = aa;
    for (int i = 0; i < 4; ++i)
    {
    unsigned int b = (int)&a[i];
    printf("%p : %x\n",&a[i],b );
    }
}

b保存的是a[i]的地址,但是正常编译会出错,

a.cpp:6:24: warning: cast from ‘int*’ to ‘int’ loses precision [-fpermissive]
  unsigned int b = (int)a;
                        ^

通过-fpermissive参数之后,error变成warning可以正常运行,某次的结果如下:

0x7ffeac7db3d0 : ac7db3d0
0x7ffeac7db3d4 : ac7db3d4
0x7ffeac7db3d8 : ac7db3d8
0x7ffeac7db3dc : ac7db3dc

为什么输出会不一样?
另外,如何正常保存变量的地址到一个数组,以便后续对这个“地址数字”进行操作?(就是后面想对0x7ffeac7db3d0这样的数据进行操作,而不是看成一个地址了)

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
左手右手慢动作

Is the subject of the question a 64-bit machine? Looking at the compilation errors, it seems that the conversion caused the error. 64-bit, pointer is 8byte, and int is 4byte. It seems to be this problem. I changed it to long long and compiled it.

#include <cstdio>
int main(int argc, char const *argv[])
{
    int aa[10]={1,2,3,4};
    int * a = aa;
    for (int i = 0; i < 4; ++i)
    {
    unsigned long long b = (long long)&a[i];
    printf("%p : %x\n",&a[i],b );
    }
}

Save the address into a long long array and treat it as an integer, then it can be processed.

巴扎黑

View error message

a.cpp:6:24: warning: cast from ‘int*’ to ‘int’ loses precision [-fpermissive]
  unsigned int b = (int)a;
                        ^

means that converting int* to int will lose precision. Because the memory sizes occupied by int* and int types are different.
Using the -fpermissive parameter forces a tolerant mode, allowing loss of accuracy.
Because usually machines are little-endian (the one you have here), so when converting integers, if more bits cannot be stored, then only the lower bits, which are the mantissa part, can be stored.

Try not to use types such as int to save memory addresses. Use the corresponding pointer type, or the void* type. You should be under linux. Using intptr_t is a good choice.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!