C library Macro - offsetof()
Description
The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.
Declaration
Following is the declaration for offsetof() Macro.
offsetof(type, member-designator)
Parameters
type -- This is the class type in which member-designator is a valid member designator.
member-designator -- This is the member designator of class type.
Return Value
This macro returns the value of type size_t which is the offset value of member in type.
Example
The following example shows the usage of offsetof() Macro.
#include <stddef.h>
#include <stdio.h>
struct address {
char name[50];
char street[50];
int phone;
};
int main()
{
printf("name offset = %d byte in address structure.\n",
offsetof(struct address, name));
printf("street offset = %d byte in address structure.\n",
offsetof(struct address, street));
printf("phone offset = %d byte in address structure.\n",
offsetof(struct address, phone));
return(0);
}
Let us compile and run the above program, this will produce the following result:
name offset = 0 byte in address structure. street offset = 50 byte in address structure. phone offset = 100 byte in address structure.