[comp.lang.c] How to USE a byte offset.

drh@romeo.cs.duke.edu (D. Richard Hipp) (06/05/90)

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 ?

In article <16787@haddock.ima.isc.com> karl@haddock.ima.isc.com
(Karl Heuer) writes:
>	#define offsetof(T,mem) ((size_t)(char *)&((T *)0)->mem)
>	#define offsetof(T,mem) ((char *)&((T *)0)->mem - (char *)0)
>	#define offsetof(T,mem) ((char *)&((T *)&X)->mem - (char *)&X)

Having obtained the byte offset of some field in a structure, is there
a standard way of using that offset?

As an example, suppose I want to write a general-purpose library routine
to sort the elements of a linked list using the merge-sort algorithm.
(This would be a counterpart to "qsort")  The routine looks like this:

void msort(void **head, int offset, int (*cmpfunc)(void*,void*));

"head" is the first element of the linked list.  Each element of the
linked list is a structure which contains (amoung other things) a
pointer to the next element in the list.  "offset" is the byte offset
to this pointer.

My question then is this:  What is the best (preferred, most portable,
etc...) way to access, for instance, the second element of the linked
list.  I've used:

#define NEXT(A) (*(void**)&(((char*)A)[offset]))
	second = NEXT(*head);

But surely, if there is a standard "offsetof" macro, there must
also be some standard way of using that macro.  What is it then?

Any comments, suggestions, or ideas are welcomed.  I will summarize
e-mail responses to the net after one week.  Tnx.