Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 863
karlphillip Avatar asked Oct 14 '10 15:10

karlphillip


2 Answers

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.

like image 81
Coincoin Avatar answered Sep 18 '22 10:09

Coincoin


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

like image 20
Armen Tsirunyan Avatar answered Sep 21 '22 10:09

Armen Tsirunyan