开发者

How to initialize a pointer to a specific memory address in C++ [duplicate]

This question already has an answer here: Pointer to a specific fixed address 开发者_运维问答 (1 answer) Closed 3 years ago.

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

#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++?


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

Example:

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

That thing hurts my eyes, and I like it.


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


This will work:

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

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


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

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

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

#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.


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:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜