zoukankan      html  css  js  c++  java
  • 【已解决】一段使用宏定义求结构体偏移量的C代码

    用一个宏定义FIND求一个结构体struc里某个变量相对于struc的偏移量,如FIND(student,a)//等于0 FIND(student,b)//等于4
    #include<stdio.h>
    #define FIND(struc,e) (unsigned int)&(((struct *)0)->e)
    struct student
    {
    int a;
    char b[20];
    double ccc;
    };

    int main()
    {
    printf("b的偏移地址为:");
    printf("%d",FIND(student,b));
    return 0;
    }

    这段代码在vc6.0中编译时会出现如下诡异的问题:

    F:\程序员面试宝典工程文件\PART2\FindMacro\main.cpp(14) : error C2027: use of undefined type '$S1'

    F:\程序员面试宝典工程文件\PART2\FindMacro\main.cpp(14) : see declaration of '$S1'

    F:\程序员面试宝典工程文件\PART2\FindMacro\main.cpp(14) : error C2227: left of '->b' must point to class/struct/union

    执行 cl.exe 时出错.

    按照字面上理解,(struct *)0表示将0强制转化为struc *型指针所指向的地址,&(((struct *)0)->e)表示取结构体指针(struct*)0的成员e的地址,因为该结构体的首地址为0,所以其实就是得到了成员e距离结构体首地址的偏移量,但为啥会出上述错误呢?
    【addon】
    原来是代码中宏定义这个地方写错了,应为: #define  FIND(stuc,e) (unsigned int)&(((struc *)0)->e)其中,struc误写为了struct,唉,写代码一定要仔细呀!
  • 相关阅读:
    位运算与变量多状态表达
    判断点是否在多边形内
    向量旋转
    小怪受击身体变红特效代码
    字典 Key值转换为数组
    Android中的Selector的使用总结
    Android 常见的工具类
    成为Android高手必须掌握的8项基本要求
    K-means算法
    Android 5.0以上获取系统运行进程信息
  • 原文地址:https://www.cnblogs.com/hust_wsh/p/2215832.html
Copyright © 2011-2022 走看看