Path: utzoo!attcan!uunet!ncrlnk!ncrcae!hubcap!gatech!uflorida!ukma!cwjcc!hal!nic.MR.NET!tank!mimsy!haven!uvaarpa!babbage!mac3n From: mac3n@babbage.acc.virginia.edu (Alex Colvin) Newsgroups: comp.lang.c Subject: Re: Something new for C? Summary: pointer subtraction Keywords: offset of vars within structures Message-ID: <399@babbage.acc.virginia.edu> Date: 10 Nov 88 21:35:20 GMT References: <73@dsoft.UUCP> <2865@ingr.UUCP> Organization: University of Virginia Lines: 14 > > way to do and have always wanted, was a precompiler command to allow me to > > use the offset of an item into a structure. for example: > #define offset(type,field) ((unsigned int)&((type *)0)->field) This works by casting a pointer to an unsigned. That sometimes isn't a good idea. To make integers out of pointers, it's best to subtract. #define offset(type,field) ( (void *)&((type *)0)->field - (void *)((type *)0) ) This gives you the offset in (void)s. You could have it in (char)s or (short)s instead. The question is, why do you want this? It doesn't belong in the precompiler, since it has to know about size and alignment constraints. Explicit pointer subtraction is usually what I want.