offsetof: Using the offsetof funcion in c

The “offsetof” function in c is useful in determining the offset of members with in a structure or union.
It is defined in the header file “stddef.h”.
The syntax is



TYPE: The type of the structure in which the offset is to be determined MEMBER: The member in the structure TYPE whose offset is required.

Example :

Let say we have a structure foo

struct foo { int i; char ch; };

The structure “foo” has a integer member which generally would of 4 bytes on a 32 bit system and a chat member which would be one byte.
Thus the offset of the member “ch” in the structure “foo” would be the number of bytes occupied by “int” which is “4”.

Here is a example code which uses “offsetof” to find the offset of ch in the structre foo.

#include#include #includestruct foo { int i; char ch; } ; main() { int size; size = offsetof(struct foo,ch); printf(“offet is = %d”,size); }

Compile the code and execute it

$ cc offset.c -o offset $ ./offset offset is = 4

Try changing adding new members to the structure foo and see how the result changes depending on the members added.

Try with the structure :

struct foo { int arr[10]; char ch; };

$ cc offset.c -o offset $ ./offset offset is 40

The offset is the size of the array which is 4 X 10 = 40.

Copyright 2017. All rights reserved.

Posted July 27, 2012 by Tux Think in category "Linux