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

Possible duplicate:
pointer to a specific fixed address

An interesting discussion about this started here, but no one was able to provide a C ++ way:

#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 suitable way to do such a thing in C ++?

+7
c ++ c casting pointers memory
source share
5 answers

In C ++, always prefer reinterpret_cast over C-cast. It is so unsightly that someone will immediately discover the danger.

Example:

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

This thing hurts me and I like it.

+18
source share

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

+1
source share

I would add that you can call the placement operator for a new one if you want the caller to call it when assigned to the specified address:

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

It is also used to cache memory 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; 
+1
source share

This will work:

 void *address=(void *) 0xdead; // But as mentioned, it non-standard address=(void *) 0xdeadbeef; // Some other address 
0
source share

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

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

In C, this is usually done using a macro:

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

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

0
source share