zoukankan      html  css  js  c++  java
  • offsetof简介

    #define offsetof(s,m) (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m))

    该宏用于求结构体中一个成员在该结构体中的偏移量。第一个参数是结构体的名字,第二个参数是结构体成员的名字。该宏返回结构体structName s中成员memberName(m)的偏移量。偏移量是size_t类型的。

    offsetof returns the offset in bytes of the specified member from the beginning of its parent data structure. It is undefined for bit fields.

    示例

    #include <stdio.h>
    #include <stddef.h>
    typedef struct
    {
    int iVal;
    int iVal2;
    }Test;
    typedef struct
    {
    char ch;
    int iNum;
    }Test2;
    int main(void)
    {
    Test t = {1, 2};
    Test2 t2 = {'t', 100};
    printf("\naddress of t : %p\naddress of t.iVal : %p\naddress of t.iVal2: %p\n\n", &t, &(t.iVal), &(t.iVal2));
    printf("offset of iVal in t: %p\n", offsetof(Test, iVal));
    printf("offset of iVal2 in t: %p\n", offsetof(Test, iVal2));
    printf("\naddress of t2 : %p\naddress of t2.ch : %p\naddress of t2.iNum: %p\n\n", &t, &(t2.ch), &(t2.iNum));
    printf("offset of ch in t2: %p\n", offsetof(Test2, ch));
    printf("offset of iNum in t2: %p\n", offsetof(Test2, iNum));
    return 0;
    }
    

     

      wps_clip_image-31628

      注意内存对齐。

    原文

    http://www.cppblog.com/lovedday/archive/2007/09/24/32801.html

    http://baike.baidu.com/view/5513779.htm

  • 相关阅读:
    Array的 map() 和 reduce()
    欧几里得算法求解最大公约数
    JavaScript Function
    JavaScript Hoisting(提升)
    activemq的事务消息
    Spring整合Activemq
    10张图带你深入理解Docker容器和镜像
    Thread类的interrupt方法
    简单工厂、工厂方法、抽象工厂笔记
    设计模式之观察者模式
  • 原文地址:https://www.cnblogs.com/mydomain/p/3114010.html
Copyright © 2011-2022 走看看