Mar 25, 2011

c tips from wang

wlh走前给大家分享的一些c tips, 我还没搞懂,先记下
#include <stdio.h>

#define get_parent(x) (struct A*)((unsigned int)x - (unsigned int)&((((struct A*)0)->j)))

struct A
{
    char name[37];
    int i;
    int j;
    int k;
    char city[37];
};

void func(int* p_int)
{
    printf("in function %x\n", (unsigned int)get_parent(p_int));
}

int main()
{
    struct A a_var;
    printf("address of a_var is %x\n", (unsigned int)&a_var);
    func(&(a_var.j));
    return 0;
}

2 comments:

  1. 应该是 get_parent_of_j
    这种代码还是用rtti的语言实现好。

    ReplyDelete
  2. 嗯,
    代码简单的演示如何通过结构体的成员变量来获取结构体的地址...
    i, j, k 等都是可以的,

    ReplyDelete

您的评论将使我blog更有动力~