finding offset of a member in C structures
Richard A. O'Keefe
ok at goanna.cs.rmit.oz.au
Tue May 21 10:35:23 AEST 1991
In article <1276 at unisql.UUCP> pckim at unisql.UUCP (Pyung-Chul Kim) writes:
> can I get the offset of member2 at *compiling time* and *portably* ?
In article <16194 at smoke.brl.mil> gwyn at smoke.brl.mil (Doug Gwyn) writes:
> Yes, but you shouldn't very often need to do so.
> Standard C provides an offsetof() macro, but you don't really need one.
In article <1991May20.201857.635 at lynx.CS.ORST.EDU>, osbornk at mist.CS.ORST.EDU (Kasey S. Osborn) writes:
> Really? I can't find a reference to offsetof() in any of my C references.
> In fact, GNU CC does not preprocess offsetof() and instead treats it as an
> external reference. Are you sure this is standard?
It sounds as though you need some up-to-date C references.
The little Plauger & Brodie handbook is cheap and excellent.
The GNU C compiler *does* understand offsetof, *provided* you #include
the right header file. Doug Gwyn wrote "Standard C provides an
offsetof() MACRO" and he chose his words carefully. *None* of the
standard C macros is available *unless* you #include an appropriate
header file. In this case the file in question is <stddef.h>,
and our copy of GCC certainly has it.
> What compiler are you using? What is the syntax of offsetof()?
offsetof(TYPE, MEMBER)
where TYPE is a type (either a typedef id or 'struct Tag'),
not a structure tag. Example:
#include <stddef.h>
struct a_struct
{
short member1;
char member2;
int member3;
};
typedef struct a_struct a_type;
main()
{
printf("%d %d %d\n",
offsetof(struct a_struct, member1),
offsetof(struct a_struct, member2),
offsetof(a_type, member3));
exit(0);
}
On an Encore Multimax I get the output "0 2 4".
--
There is no such thing as a balanced ecology; ecosystems are chaotic.
More information about the Comp.lang.c
mailing list