offsetof 例子

/* offsetof example */

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

/************************************************************************/
/* Macro OBJECT_HEAD_ADDRESS : calculate the struct's address according
/* to one of its member's address
/************************************************************************/
#define OBJECT_HEAD_ADDRESS(ClassName,MemberName,Addre) /
Addre - offsetof(ClassName, MemberName)

struct S
{
int ID;
char *addr;
char name[20];
};

struct S1
{
S employee;
char *title;
};

struct S2
{
char singlechar;
int arraymember[10];
char anotherchar;
};

int main(int argc, char* argv[])
{
/* Example 1
S2 s2 = {'a', 10, 'b'};
int head = int(&(s2.singlechar));
int memb = int(&(s2.anotherchar));

int i = OBJECT_HEAD_ADDRESS(S2, anotherchar, memb);

printf ("offsetof(S2, singlechar) is %d/n", offsetof(S2, singlechar));
printf ("offsetof(S2, arraymember) is %d/n", offsetof(S2, arraymember));
printf ("offsetof(S2, anotherchar) is %d/n", offsetof(S2, anotherchar));
printf("s2.anotherchar's address is %x ==> s2's address is %x/n", memb, i);
*/
/* Example 2
S s = {100, "Nanjing", "Thomas"};
int id = int(&(s.ID));
int ad = int(&(s.addr));
int nm = int(&(s.name));

int j = OBJECT_HEAD_ADDRESS(S, addr, ad);

printf ("offsetof(S, ID) is %d/n", offsetof(S, ID));
printf ("offsetof(S, addr) is %d/n", offsetof(S, addr));
printf ("offsetof(S, name) is %d/n", offsetof(S, name));
printf ("s.ID's address : %x/ns.addr's address : %x/ns.name's address : %x/n", id, ad, nm);
printf("s.addr's address is %x ==> s's address is %x/n", ad, j);
*/
/* Example 3 */
S1 s1 = {{100, "Nanjing", "Thomas Chen"},"Thomas Chen"};
int td = int(&(s1.title));
int k = OBJECT_HEAD_ADDRESS(S1, title, td);

printf ("offsetof(S1, employee) is %d/n", offsetof(S1, employee));
printf ("offsetof(S1, title) is %d/n", offsetof(S1, title));
printf("s1.title's address is %x ==> s1's address is %x/n", td, k);

return 0;
}
/* Example 1 Output */
offsetof(S2, singlechar) is 0
offsetof(S2, arraymember) is 4
offsetof(S2, anotherchar) is 44
s2.anotherchar's address is 12ff7c ==> s2's address is 12ff50

/* Example 2 Output */
offsetof(S, ID) is 0
offsetof(S, addr) is 4
offsetof(S, name) is 8
s.ID's address : 12ff64
s.addr's address : 12ff68
s.name's address : 12ff6c
s.addr's address is 12ff68 ==> s's address is 12ff64

/* Example 3 Output */
offsetof(S1, employee) is 0
offsetof(S1, title) is 28
s1.title's address is 12ff7c ==> s1's address is 12ff60

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值