简体   繁体   中英

C++ assign a variable pointer address

I want to receive a variable of type DWORD which will contain address pointer float *.
If I write this:

float *Object = 5;  
std::cout << &Object;

It gives me exactly the value that I want (ie: 0F235C1A ). Can you tell me how to assign this value to DWORD for using it in my Memory Write function?
Trying:

DWORD ObjAddress = &Object;

I got compiler error: cannot convert from 'float *' to 'DWORD'

You just need to cast your &Object;

DWORD ObjAddress = (DWORD)&Object;

And I think that will solve your problem.

I think you can use reinterpret_cast like this (replace unsigned long with DWORD)

#include <iostream>

int main(void)
{
    float *object  = new float;

    *object = 5;

    unsigned long objAddress = reinterpret_cast<unsigned long>(&object);

    std::cout<<objAddress<<std::endl;
    return 0;
}

I don't understand your object definition:

float *Object = 5;  

The 5 should be an address? a value?

See following code, maybe it is what you want.

float Object = 5;
int ObjAddress =  (int)&Object;
cout << "object adr1: "<< hex << &Object << endl;
cout << "object adr2: "<< hex << ObjAddress << endl;

Output

object adr1: 0x28ff08
object adr2: 28ff08

Or when you really need the object as a pointer

float value = 5;
float *Object = &value;
int ObjAddress =  (int)&Object;
cout << "object adr1: "<< hex << &Object << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM