offsetof() macro

Doug Gwyn gwyn at smoke.BRL.MIL
Mon Aug 28 13:33:13 AEST 1989


In article <175 at crdos1.crd.ge.COM> davidsen at crdos1.crd.ge.COM (Wm E Davidsen Jr) writes:
>  What good is offsetof?

Extracted from <sys/dirent.h>:

struct dirent				/* data from getdents()/readdir() */
	{
	long		d_ino;		/* inode number of entry */
	off_t		d_off;		/* offset of disk directory entry */
	unsigned short	d_reclen;	/* length of this record */
	char		d_name[1];	/* name of file */	/* non-POSIX */
	};

/* The following nonportable ugliness could have been avoided by defining
   DIRENTSIZ and DIRENTBASESIZ to also have (struct dirent *) arguments. */
#define	DIRENTBASESIZ		(((struct dirent *)0)->d_name \
				- (char *)&((struct dirent *)0)->d_ino)
#define	DIRENTSIZ( namlen )	((DIRENTBASESIZ + sizeof(long) + (namlen)) \
				/ sizeof(long) * sizeof(long))

This, as the comment indicates, is nonportable and ugly.  I leave it as a
simple exercise to the reader to figure out how offsetof() can improve this.



More information about the Comp.lang.c mailing list