首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

已知struct结构体里面的某一变量的地址,问如何求struct的首地址

2013-06-25 
已知struct结构体里面的某一变量的地址,问怎么求struct的首地址?//#includestdio.hstruct A {...int i.

已知struct结构体里面的某一变量的地址,问怎么求struct的首地址?
//#include<stdio.h>

struct A 
{
...
int i;
...
};

//int main()
//{
//printf("%p\n",&(((struct A *)0)->i));
//return 0;
//}
已知i的地址,问怎么求struct的首地址。。。。室友思路如程序所叙,求对i的偏移量,然后自然而然可求A的首地址。但我没听明白,求高手解释。。。
[解决办法]

&(((struct A *)0)->i

求的是i相对于结构其实地址的相对偏移量。。原理就是设首地址为0,求i的绝对地址。。
既然求出了相对偏移量,又知道i的地址。。首地址不就&i-offset。。
[解决办法]
考虑一下使用
offsetof


#include <stddef.h>
#include <stdio.h>

struct A {
char c;
short s;
int i;
};

int main(int argc, char *argv[])
{
struct A a;

printf("%p\n", &a);
printf("%p\n", &a.i);
printf("%d\n", offsetof(struct A, i));
return 0;
}

热点排行