我可以直接将地址分配给指针吗?如果是这样,该怎么做? [英] Can I directly assign an address to a pointer? If so, how to do that?

查看:33
本文介绍了我可以直接将地址分配给指针吗?如果是这样,该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
  int a = 2; // address is 0x7ffeefbff58c
  int *b = &a;
  std::cout << "address of a: " << b << std::endl;
  return 0;
}

我在地址0x7ffeefbff58c中有一个int变量a,但是我可以直接为int * b分配0x7ffeefbff58c吗?

I have my int variable a at address 0x7ffeefbff58c, but can I directly assign int* b with 0x7ffeefbff58c?

我尝试了int * b = 0x7ffeefbff58c;但是有一个错误提示无法用'long'类型的右值初始化'int *'类型的变量",所以我必须使用(& a)的地址来初始化指针吗?还是有其他方法可以做到?

I tried int * b = 0x7ffeefbff58c; But there is an error says "cannot initialize a variable of type 'int *' with an rvalue of type 'long'", so do I have to use the address of a (&a) to initialize the pointer? or there is other way to do it?

推荐答案

我可以直接用0x7ffeefbff58c分配int * b吗?

can I directly assign int* b with 0x7ffeefbff58c?

从技术上讲,是的.

如果是,该怎么做?

If so, how to do that?

带有重新解释的演员表.

With reinterpret cast.

但是要意识到,总体上绝对不能保证 a 位于地址0x7ffeefbff58c中.这样,将整数重新解释为指针就无能为力了.使用局部变量执行此操作将是毫无意义的.

But do realise that there is absolutely no guarantee in general that a would be in the address 0x7ffeefbff58c. As such, there isn't much that you can do with such integer reinterpreted as a pointer. Doing this with a local variable would be pointless.

将整数解释为指针很有用的情况是,某些嵌入式系统会保留一些恒定的内存地址以用于特殊目的.

A case where interpreting integer as a pointer is useful is some embedded systems that reserve some constant memory addresses for special purposes.

这篇关于我可以直接将地址分配给指针吗?如果是这样,该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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