• 【已解决】一段使用宏定义求结构体偏移量的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,唉,写代码一定要仔细呀!
  • 相关阅读:
    scrum项目冲刺_day03总结
    scrum项目冲刺_day02总结
    关于Map的PUT的value值的问题
    oracle见表
    sql优化(转载)
    oracle注意事项
    mybatis中jdbcType的作用和是否必须
    spring 的web.xml的加载顺序
    spring 另开线程时的注入问题
    获取客户端的ip
  • 原文地址:https://www.cnblogs.com/hust_wsh/p/2215832.html
Copyright © 2020-2023  润新知