如何在 C++ 中初始化指向特定内存地址的指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3934775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:05:35  来源:igfitidea点击:

How to initialize a pointer to a specific memory address in C++

c++cpointersmemorycasting

提问by karlphillip

An interesting discussion about this started herebut no one have been able to provide the C++ way of doing:

一个有趣的讨论从这里开始但没有人能够提供 C++ 的做法:

#include <stdio.h>

int main(void)
{
  int* address = (int *)0x604769; 
  printf("Memory address is: 0x%p\n", address);

  *address = 0xdead; 
  printf("Content of the address is: 0x%p\n", *address);

  return 0;
}

What is the most appropriate way of doing such a thing in C++?

在 C++ 中做这样的事情最合适的方法是什么?

回答by Coincoin

In C++, always prefer reinterpret_castover a C-cast. It's so butt ugly that someone will immediately spot the danger.

在 C++ 中,总是reinterpret_cast比 C-cast更喜欢。它的屁股丑得让人立刻发现危险。

Example:

例子:

int* ptr = reinterpret_cast<int*>(0x12345678);

That thing hurts my eyes, and I like it.

那东西刺痛了我的眼睛,我喜欢它。

回答by Armen Tsirunyan

There is NO standard and portable way to do so. Non-portable ways may include reinterpret_cast(someIntRepresentingTheAddress).

没有标准和便携的方法可以做到这一点。不可移植的方式可能包括 reinterpret_cast(someIntRepresentingTheAddress)。

回答by Michael Goldshteyn

This will work:

这将起作用:

void *address=(void *) 0xdead; // But as mentioned, it's non-standard

address=(void *) 0xdeadbeef; // Some other address

回答by Thomas Matthews

In C++, I prefer to declare the pointers as constant pointers in a header file:

在 C++ 中,我更喜欢在头文件中将指针声明为常量指针:

volatile uint8_t * const UART_STATUS_REGISTER = (uint8_t *) 0xFFFF4000;

In the C language, this is usually implemented using a macro:

在 C 语言中,这通常使用宏来实现:

#define UART_STATUS_REGISTER ((volatile uint8_t * const) 0xFFFF4000)

In the rest of the source code, the memory address is referenced via the symbolic name.

在源代码的其余部分,内存地址是通过符号名称引用的。

回答by Dan

I would add that you can call the placement operator for new if you want an objects constructor called when assigning it at the specified address:

我要补充的是,如果您希望在指定地址分配对象时调用一个对象构造函数,则可以为 new 调用放置运算符:

int *pLoc = reinterpret_cast<int*>(0x604769);
int *address = new (pLoc) int (1234); // init to a value

This is also used for memory caching objects. Create a buffer and then assign an object to it.

这也用于内存缓存对象。创建一个缓冲区,然后为其分配一个对象。

unsigned char *pBuf = new unsigned char[sizeof(CMyObject) + alignment_size];
allign_buf(pBuf);
CMyObject *pMyObj = new (pBuf) CMyObject;