offsetof 函数解析

NAME
       offsetof - offset of a structure member

SYNOPSIS
       #include <stddef.h>

       size_t offsetof(type, member);

DESCRIPTION
       The macro offsetof() returns the offset of the field member from the start of the structure type.

       This  macro  is useful because the sizes of the fields that compose a structure can vary across implementations, and compilers may
       insert different numbers of padding bytes between fields.  Consequently, an element's offset is not necessarily given by  the  sum
       of the sizes of the previous elements.

       A compiler error will result if member is not aligned to a byte boundary (i.e., it is a bit field).

RETURN VALUE
       offsetof() returns the offset of the given member within the given type, in units of bytes.

CONFORMING TO
       C89, C99, POSIX.1-2001.

原型:

#define offsetof(s,m) (size_t)&(((s *)0)->m)

example:

    #include <stdio.h>
    #include <stddef.h>

    typedef struct node
    {
            int id;
            int age;
            char name[12];
            char address[32];
    }node;

    int main(void)
    {
            printf("id in node size_t seek %d\n", (size_t)&(((node *)0)->id)); // 原型

            printf("id in node size_t seek %d\n", offsetof(node, id));
            printf("age in node size_t seek %d\n", offsetof(node, age));
            printf("name in node size_t seek %d\n", offsetof(node, name));
            printf("address in node size_t seek %d\n", offsetof(node, address));

            return 0;
    }


    ./offsetof  
输出结果:
    id in node size_t seek 0
    id in node size_t seek 0
    age in node size_t seek 4
    name in node size_t seek 8
    address in node size_t seek 20

解析:

(size_t)&(((node *)0)->id)
    (node *)0   ==>  malloc(sizeof(node))  ==> node *pnode;
因为id 是node结构体的第一个元素,在此 去pnode->id  的地址 其实与 pnode 的地址是一致的,
可以使用 %p 查看输出地址信息

    printf("pnode = %p\n",  pnode);
    printf("&(pnode->id) = %p\n",  &(pnode->id));

    pnode = 0x1912010
    &(pnode->id) = 0x1912010
故:
(node *)0  ==>  node *pnode = (node *)0; 
此时的pnode = 0x0000;

&(((node *)0)->id)  ==> &(pnode->id)  即 id 的地址;

最后强转为size_t ;
欣赏此文? 求鼓励,求支持!