zoukankan      html  css  js  c++  java
  • [转帖]查看结构体成员的大小和偏移地址的方法


    [原文: http://www.cnitblog.com/shosh/archive/2008/05/06/posizeOfStruct.html ]

    这个是不小心被我撞见的,看到#define宏定义比较特别,仔细看了一下,发现原来有如此作用(请不要怪我少见多怪哦)。
    自己编写一小程序试之,贴出代码与运行结果与大家共享。

    #include <stdio.h>
     
    #define PACKVALUE 4
    #pragma pack(push)
    #pragma pack(PACKVALUE)        
    typedef 
    struct
    {
            
    char sa;
            
    double sb;
            
    int sc;
    }
     innerS;
     
    typedef 
    struct
    {
            
    int a;
            
    char b;
            
    short c;
            innerS d[
    2];
    }
     testS;
     
    #pragma pack(pop)
     
    typedef unsigned 
    long dword;
     
    #define FSIZE(type, field) sizeof(((type*)0)->field)    //字段所占内存大小(字节)
    #define FPOS(type, field) ((dword) & ((type*)0)->field)   //字段在结构体中的偏移位置
     
    int main(void)
    {
            printf(
    "#pragma pack(%d):\nsizeof(char)=%d; sizeof(short)=%d; sizeof(int)=%d; sizeof(double)=%d\n\n",
                            PACKVALUE, 
    sizeof(char), sizeof(short), sizeof(int), sizeof(double));
     
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, a), FPOS(testS, a));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, b), FPOS(testS, b));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, c), FPOS(testS, c));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d), FPOS(testS, d));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d[0]), FPOS(testS, d[0]));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d[0].sa), FPOS(testS, d[0].sa));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d[0].sb), FPOS(testS, d[0].sb));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d[0].sc), FPOS(testS, d[0].sc));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d[1]), FPOS(testS, d[1]));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d[1].sa), FPOS(testS, d[1].sa));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d[1].sb), FPOS(testS, d[1].sb));
            printf(
    "FSIZE = %d, FPOS = %d\n", FSIZE(testS, d[1].sc), FPOS(testS, d[1].sc));
            
    return 0;
    }
  • 相关阅读:
    安装SQL sever2008时显示重新启动计算机规则失败,应该怎么解决?
    C#获取当前日期时间(转)
    使用JQUERY实现页面局部刷新
    Metal渲染:实现画面比例功能
    Metal渲染:实现旋转/翻转功能
    依赖注入浅析
    iOS 消息推送实现 APNS
    使用#pragma阻止一些warnings
    github 多帐户使用
    Swift 实现Bitmask Option(Enum)
  • 原文地址:https://www.cnblogs.com/Andrewz/p/1186834.html
Copyright © 2011-2022 走看看