Thursday, Aug 16th

Last update12:59:40 PM GMT

Can we determine the offset of a field within a structure and directly access that element?

Write e-mail

The offsetof() macro(<stddef.h>) does exactly this.

A probable implementation of the macro is

	#define offsetof(type, mem) ((size_t)((char *)&((type *)0)->mem - (char *)(type *)0))


This can be used as follows. The offset of field a in struct mystruct is

	offset_of_a = offsetof(struct mystruct, a)


If structpointer is a pointer to an instance of this structure, and field a is an int, its value can be set indirectly with

	*(int *)((char *)structpointer + offset_of_a) = some_value;


Share this post

Web Hosting