Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static_cast integer address to pointer

Tags:

c++

casting

Why do you need a C-style cast for the following?

int* ptr = static_cast<int*>(0xff); // error: invalid static_cast from type 'int' 
                                    // to type 'int*'
int* ptr = (int*) 0xff; // ok.
like image 401
user4052464 Avatar asked Sep 18 '14 00:09

user4052464


2 Answers

static_cast can only cast between two related types. An integer is not related to a pointer and vice versa, so you need to use reinterpret_cast instead, which tells the compiler to reinterpret the bits of the integer as if they were a pointer (and vice versa):

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

Read the following for more details:

Type conversions

like image 143
Remy Lebeau Avatar answered Oct 05 '22 02:10

Remy Lebeau


You need a C-style cast or directly the reinterpret_cast it stands for when casting an integer to a pointer, because the standard says so for unrelated types.

The standard mandates those casts there, because

  1. you are doing something dangerous there.
  2. you are doing something very seldom useful.
  3. you are doing something highly implementation-dependent.
  4. most times, that is simply a programming-error.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
Regular cast vs. static_cast vs. dynamic_cast

like image 36
Deduplicator Avatar answered Oct 05 '22 01:10

Deduplicator