指针只是整数吗? [英] Is pointer just an integer?

查看:66
本文介绍了指针只是整数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我知道数据对象的地址,是否可以将地址存储为整数并将整数用作指针?

If I know the address of an data object, could I store the address as an integer and operate the integer as a pointer?

例如,

void main(){
    long a = 101010;
    long *p = &a;
    long b = p;
    printf("%lld\n", *(long*)b);
}

它总是安全吗?

注释: long b = p; 产生警告:

Initialization makes integer from pointer without a cast

但是,程序会打印 101010 .

推荐答案

标准不保证此类强制转换将始终有效.

It's not guaranteed by the standard that such cast would always work.

要以整数类型存储指针,请使用 intptr_t (或其未签名的堂兄弟 uintptr_t ).可以保证将 void * 指针转换为此类类型,然后再转换回原来的值.

To store a pointer in an integral type, use intptr_t (or its unsigned cousin uintptr_t). It's guaranteed to convert void * pointers to such types and convert back, resulting the same value.

请注意,这些类型是可选的.

Note that these types are optional.

这篇关于指针只是整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆