Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      offsetof

      From cppreference.com
      <c‎ |types
       
       
       
      Defined in header<stddef.h>
      #define offsetof(type, member) /*implementation-defined*/

      The macrooffsetof expands to aninteger constant expression of typesize_t, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified subobject, including padding if any.

      Given an objecto of typetype with static storage duration,&(o.member) shall be an address constant expression and point to a subobject ofo. Otherwise, the behavior is undefined.

      If the type name specified intype contains a comma not between matching parentheses, the behavior is undefined.

      (since C23)

      Contents

      [edit]Notes

      Ifoffsetof is applied to a bit-field member, the behavior is undefined, because the address of a bit-field cannot be taken.

      member is not restricted to a direct member. It can denote a subobject of a given member, such as an element of an array member.

      Even though it is specified in C23 that specifying a new type containing an unparenthesized comma inoffsetof is undefined behavior, such usage is generally not supported even in earlier modes:offsetof(struct Foo{int a, b;}, a) generally fails to compile.

      typeof can be used to avoid the bad effect of commas in the definition of a new type, e.g.offsetof(typeof(struct{int i, j;}), i) is well-defined.

      (since C23)

      [edit]Example

      Run this code
      #include <stdio.h>#include <stddef.h> 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));}

      Possible output:

      the first element is at offset 0the double is at offset 8

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C standards.

      DRApplied toBehavior as publishedCorrect behavior
      DR 496C89only structs and struct members were mentionedunions and other subobjects are also supported

      [edit]See also

      unsigned integer type returned by thesizeof operator
      (typedef)[edit]
      C++ documentation foroffsetof
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=c/types/offsetof&oldid=170432"

      [8]ページ先頭

      ©2009-2025 Movatter.jp