C Data Type Functions - C offsetof






Return member offset

Prototype

size_t offsetof (type,member)

Parameter

This function has the following parameter.

type
A type in which member is a valid member designator.
member
A member of type.

Return

A value of type size_t with the offset value of member in type.

Example


#include <stdio.h> /* printf */
#include <stddef.h> /* offsetof */
/* ww  w. ja  v  a 2 s  .  c o m*/
struct foo {
  char a;
  char b[10];
  char c;
};

int main ()
{
  printf ("offsetof(struct foo,a) is %d\n",(int)offsetof(struct foo,a));
  printf ("offsetof(struct foo,b) is %d\n",(int)offsetof(struct foo,b));
  printf ("offsetof(struct foo,c) is %d\n",(int)offsetof(struct foo,c));
  
  return 0;
} 

       

The code above generates the following result.





Example 2


#include <stdio.h>
#include <stddef.h>
 //from   w  w  w  . j  ava 2 s  .  co m
struct S {
    char c;
    double d;
};
 
int main(void)
{
    printf("the first element is at offset %zu\n", offsetof(struct S, c));
    printf("the double is at offset %zu\n", offsetof(struct S, d));
}

The code above generates the following result.