zoukankan      html  css  js  c++  java
  • offset宏

    【1】offset宏的作用?

    答案:自己查MSDN(呵呵!我也不懂。)

    查询结果如下:

    Retrieves the offset of a member from the beginning of its parent structure.

    size_t  offsetof(structName,  memberName);

    Parameters 

    structName: Name of the parent data structure.

    memberName : Name of the member in the parent data structure for which to determine the offset.

    Return Value

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

    Remarks

    The offsetof macro returns the offset in bytes of memberName from the beginning of the structure specified by structName. You can specify types with the struct keyword.

    好吧!不要给我说看不懂,看不懂就想问你:“你好!大学四级没过吧?”

    那么,关于这个查询结果的学习过程如下,假使定义了一个结构体:A,定义其指针pA。示例代码如下:

    1 struct A
    2 {
    3     int i;
    4     int j;
    5 };
    6 
    7 struct A *pA;

    这时,pA作为一个Pointer, 指向某一确定的内存地址,比如0x1234。
    而 pA->i 整体是一个int型变量,其地址表示为&(pA->i) ,'&'为取址运算符; 
    那么&(pA->i)一定等于0x1234,因为i是结构体A的第一个变量成员。 
    而&(pA->j)一定是0x1234 + 0x4 = 0x1238。因为sizeof(int) = 4;

    现在试想一下,我们把结构体的指针值如果作为0,会得到什么结果呢?

    也就是说:

    0------>(A *)0

    原来是数值0,现在为结构体指针类型。尽管类型不同,但其值不变。

    &(((A *)0)->j)求出字段j的地址值,但由于首地址是0。

    所以,(size_t)(&(((A *)0)->j))值将是字段j相当于首地址的偏移值。

    具体示例代码如下:

     1 #include<iostream>
     2 using  namespace std;
     3 
     4 #define  offset(s,a)   ((size_t)(&(((s *)0)->a)))
     5 
     6 struct  s
     7 {
     8     int  a;
     9     char d;
    10     int  b;
    11     char c;
    12 };
    13 
    14 void main()
    15 {
    16     cout<<offset(s,c)<<endl;   //12
    17 }
    作者:kaizen
    声明:本文版权归作者和博客园共有,欢迎转载。但未经作者同意必须保留此声明,且在文章明显位置给出本文链接,否则保留追究法律责任的权利。
    签名:顺序 选择 循环
  • 相关阅读:
    js事件监听机制(事件捕获)
    js预解析
    前端工程师也要关注代码版本控制
    BOM跟DOM的区别和关联
    web开发,click,touch,tap事件浅析
    prototype
    CSS:haslayout
    canvas画图
    第一个json解析:ps:(内容待完善)
    json解析实例
  • 原文地址:https://www.cnblogs.com/Braveliu/p/2839553.html
Copyright © 2011-2022 走看看