cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : C Library : cstddef (stddef.h) : offsetof
 
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
C Library
cassert (assert.h)
cctype (ctype.h)
cerrno (errno.h)
cfloat (float.h)
climits (limits.h)
clocale (locale.h)
cmath (math.h)
csetjmp (setjmp.h)
csignal (signal.h)
cstdarg (stdarg.h)
cstddef (stddef.h)
cstdio (stdio.h)
cstdlib (stdlib.h)
cstring (string.h)
ctime (time.h)
cstddef (stddef.h)
macros:
· NULL
· offsetof
types:
· ptrdiff_t
· size_t

-

offsetof macro
offsetof (type,member)
<cstddef>

Return member offset

This macro with functional form returns the offset value in bytes of member member in the structure type type.

The value returned is an unsigned integral value of type size_t with the amount of bytes between the specified member and the beginning of its structure.

Because of the extended functionality of structs in C++, in this language, the use of offsetof is restricted to "POD types", which for classes, more or less corresponds to the C concept of struct (although non-derived classes with only public non-virtual member functions and with no constructor and/or destructor would also qualify as POD).

Parameters

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

Return value

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

Example

/* offsetof example */
#include <stdio.h>
#include <stddef.h>

struct mystruct {
  char singlechar;
  char arraymember[10];
  char anotherchar;
};

int main ()
{
  printf ("offsetof(mystruct,singlechar) is %d\n",offsetof(mystruct,singlechar));
  printf ("offsetof(mystruct,arraymember) is %d\n",offsetof(mystruct,arraymember));
  printf ("offsetof(mystruct,anotherchar) is %d\n",offsetof(mystruct,anotherchar));
  
  return 0;
}

Output:

offsetof(mystruct,singlechar) is 0
offsetof(mystruct,arraymember) is 1
offsetof(mystruct,anotherchar) is 11
© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us