pointer subtraction

J

junky_fellow

Guys,

I want to find out an offset of a member inside a structure.
Although, there is a macro (offsetof) available to do this. Still, I
have one question. Can I subtract the address of the member from the
address of structure to get the offset ? If not, what are the reasons
for not doing this subtraction ?

Thanks for any help ...
 
J

Justin Spahr-Summers

Guys,

I want to find out an offset of a member inside a structure.
Although, there is a macro (offsetof) available to do this. Still, I
have one question. Can I subtract the address of the member from the
address of structure to get the offset ? If not, what are the reasons
for not doing this subtraction ?

Thanks for any help ...

You acknowledge the existence of offsetof() but then proceed to ask
for ways to re-implement the exact same behavior... why do you need to
do this?
 
C

Chris Dollin

I want to find out an offset of a member inside a structure.
Although, there is a macro (offsetof) available to do this. Still, I
have one question. Can I subtract the address of the member from the
address of structure to get the offset ?
Yes.

If not, what are the reasons
for not doing this subtraction ?

(a) It's only defined to work if you /have/ an instance of the structure.
(Otherwise, there's nothing to take the address of.)

(b) offsetof exists. Someone's done the work for me. Laziness rules!
 
A

Army1987

Guys,

I want to find out an offset of a member inside a structure.
Although, there is a macro (offsetof) available to do this. Still, I
have one question. Can I subtract the address of the member from the
address of structure to get the offset ?
You have to convert them both to unsigned char *.
If not, what are the reasons for not doing this subtraction ?
Because there's no need to reinvent the wheel.
 
D

David Thompson

Other way, obviously: subtract base address from member address.
If the only action is to subtract one pointer from another, any of the
char types will work.
Right.
Right.

- formerly david.thompson1 || achar(64) || worldnet.att.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top