Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uwm.edu!cs.utexas.edu!wuarchive!udel!princeton!phoenix!pfalstad From: pfalstad@phoenix.Princeton.EDU (Paul John Falstad) Newsgroups: comp.lang.c Subject: Re: How to get a byte offset Message-ID: <16821@phoenix.Princeton.EDU> Date: 29 May 90 06:11:28 GMT References: <1990May28.034643.6962@cs.umn.edu> <16802@phoenix.Princeton.EDU> Reply-To: pfalstad@phoenix.Princeton.EDU (Paul John Falstad) Distribution: usa Organization: Princeton University, NJ Lines: 26 In article <16802@phoenix.Princeton.EDU> I write: >In article <1990May28.034643.6962@cs.umn.edu> swie@cs.umn.edu (S. T. Tan) writes: >>Is there an easy way to get the byte offset of a field in a structure without >>counting it manually ? >The first way is just to add up all the sizeof values of a, b, and c. Oops #1: This doesn't work, since there might be padding. (It was a stupid suggestion anyway, and unnecessary, as it turns out.) Oops #2: > d_offset = (char *) &foo->d - (char *) foo; >Of course, the result isn't a constant, and code is generated. You Well, I'm not sure about the above example, but even Manx got this right: #define d_offset ((int) &(((struct foo *) 0)->d)) The result IS an integer constant. You can even use it for an array size, although it may not be portable because of the NULL pointer. -- Paul Falstad PLINK:Hypnos GEnie:P.FALSTAD net:pfalstad@phoenix.princeton.edu Disclaimer: My opinions, which belong to me and which I own, are mine. -Anne Elk (not AN elk!) The sun never set on the British empire because the British empire was in the East and the sun sets in the West.