Chinaunix首页 | 论坛 | 博客
  • 博客访问: 526134
  • 博文数量: 114
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1840
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-05 21:57
文章分类

全部博文(114)

文章存档

2010年(17)

2009年(26)

2008年(71)

我的朋友

分类: C/C++

2008-04-10 12:29:39

 话不多说,例子一看便明:

#include <stdio.h>
#include <stdlib.h>

#pragma pack(2)

typedef struct {
    int a;
    char b;
    int c;
    float d;
    double e;
    char g;
    char h;
}test_T;

#define offset(T, f) ((int)(&(((T*)0)->f)))

#define print_f(T, f); printf(#T"->"#f": %d\n", offset(T, f));

int main(int argc, char* argv[])
{
    print_f(test_T, a);
    print_f(test_T, b);
    print_f(test_T, c);
    print_f(test_T, d);
    print_f(test_T, e);
    print_f(test_T, g);
    print_f(test_T, h);
    return 0;
}

输出结果:

test_T->a: 0
test_T->b: 4
test_T->c: 6
test_T->d: 10
test_T->e: 14
test_T->g: 22
test_T->h: 23


测试环境:

Linux version 2.6.23.1-42.fc8 (kojibuilder@xenbuilder4.fedora.phx.redhat.com) (gcc version 4.1.2 20070925 (Red Hat 4.1.2-33)) #1 SMP Tue Oct 30 13:55:12 EDT 2007

阅读(1605) | 评论(0) | 转发(0) |
0

上一篇:敢问路在何方

下一篇:奔头

给主人留下些什么吧!~~