Skip to main content
gamedev.net
🔒 Locked

How to... Pointers

Started by Prozak 7 replies 200+ views
Original Post
Prozak
Prozak
Hi, lets imagine i have the following variables: int a; char b; long c; CClass d; int vpos; Each one of the variables starts at a certain address n memmory, for example a starts at 0x0045f33... How can i get this address into vpos? i would even like to get where in memmory d (which is a class) starts... thanx for any input on this, this must be easy, i''m just not seing how to do it...

[Hugo Ferreira][Positronic Dreams]
Visit my WebSite!

Neosmyle
Neosmyle
Um...why?
SysOp_1101
SysOp_1101
What''s wrong with using the ''&'' operator? Then (I do believe) you should be able to do something like:

vpos = (int)(&d);
SysOp_1101
Prozak
Prozak
I have this code:


    
long mpos;
int d;
int *p;
CClass cc;

d=66;
mpos = (int)(&d);

// mpos = (CClass)(&cc);




This works great, i now have d's address in mpos.
But how can i get this to work on more complex types?
The commented line does not work, gives this error:
"error C2440: type cast: cannot cnvert from "class CClass *" to "class CClass". No constructor bla bla...

Also, now that i have d's position in mpos, how do i get p
to point to d, using only the data in mpos?

You guys are really helpful, i cant figure this out


[Hugo Ferreira][Positronic Dreams]
Visit my WebSite!



[edited by - pentium3id on February 25, 2003 12:45:34 AM]
Neosmyle
Neosmyle
Hm...ever heard the words "type safety"?
SysOp_1101
SysOp_1101
Miserables suggestion of 'vpos = reinterpret_cast(&a);' is the best way to go (while the C style casting works, it's not type safe).

As for the line that's giving you the error, it should be changed to:


  
mpos = reinterpret_cast<int>(&cc);


The way it's written, your trying to convert the address of the CClas object back to a CClas object (can't be done as far as I know).

To answer your question of working with complex types, your mpos variable will hold the address of the beginning of the class. You 'should' be able to access individual members of the class by using the base address plus an offset into the class. I'm not 100% sure this will work however because I've only found need to use this in assembly. By doing this, you're basically trying to invalidate everything a well written class is supposed to be. Direct access pretty much violates any type of data abstraction you had built into the class. Structs with only data and no functions are better suited to doing this.

Just my $.02.

[edited by - SysOp_1101 on February 26, 2003 2:50:29 AM]
SysOp_1101

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.