[轉帖]查看結構體成員的大小和偏移地址的方法


[原文: 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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章