Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ treat the address location as an integer

I want to know if there is anyway that I can store the address location of a variable as an integer value. For example, let's say that I have a number stored in some location in memory

int i= 20;

and we know that for example, the location of the variable i is 0x77C79AB2. e.g.

int * ip = &i;

so we know that ip = 0x77C79AB2.

But at this point the variable ip is just a pointer. But let's say that I now want to store the address location 0x77C79AB2 into a variable of type int (NOT of type Pointer).

so, somehow I want to be able to make another variable of type (int) to actually store the number 0x77C79AB2 as a value not as a address location.

int a = 0x77C79AB2;

So, I could do whatever I want with the variable a. For example, I want to treat a as an integer and add a hex number 0x20 to it.

e.g.

int b = a + 0x20 =  0x77C79AB2 + 0x20 = 0x77C79AD2

Is this possible? How could I make this assignment ?

like image 955
Rudy01 Avatar asked Aug 10 '14 02:08

Rudy01


1 Answers

Pointers are not integers. If you want to store a pointer value, you should almost always store it in a pointer object (variable). That's what pointer types are for.

You can convert a pointer value to an integer using a cast, either a C-style cast:

int foo;
int addr = (int)&foo;

or using a C++-style cast:

int foo;
int addr = reinterpret_cast<int>(&foo);

But this is rarely a useful thing to do, and it can lose information on systems where int happens to be smaller than a pointer.

C provides two typedefs intptr_t and uintptr_t that are guaranteed to be able to hold a converted pointer value without loss of information. (If no integer types are wide enough for this, intptr_t and uintptr_t will not be defined). These are declared in the <stdint.h> header, or <cstdint> in C++:

#include <stdint.h>
// ...
int foo;
uintptr_t addr = reinterpret_cast<uintptr_t>(&foo);

You can then perform integer arithmetic on the value -- but there's no guarantee that the result of any arithmetic is meaningful.

I suspect that you're trying to do something that doesn't make much sense. There are rare cases where it makes sense to convert a pointer value to an integer and even rarer cases where it makes sense to perform arithmetic on the result. Reading your question, I don't see any real indication that you actually need to do this. What exactly are you trying to accomplish? It's likely that whatever you're trying to do, there's a cleaner way to do it.

like image 164
Keith Thompson Avatar answered Oct 21 '22 15:10

Keith Thompson