offsetof宏—求结构体中一个成员在该结构体中的偏移量

原创
2014/04/14 09:44
阅读数 902

该宏用于求结构体中一个成员在该结构体中的偏移量。

该宏被写作:

size_t offsetof( structName, memberName );

第一个参数是结构体的名字,

第二个参数是结构体成员的名字。

该宏返回结构体structName中成员memberName的偏移量。

偏移量是size_t类型的。

=========================================================================

#include<stdio.h>
#include<stdlib.h>
#include <stddef.h>//offsetof(type,member);
typedef struct
{
  char a;
  int b;
  int c;
}node_t;
int main()
{
  unsigned char *p = NULL;
  node_t node;
  node.a = 1;
  node.b = 22;
  node.c = 33; 
 
  p = (unsigned char *)&node;
  printf("size = %d\n",offsetof(node_t,c));
  printf("node.c = %d\n",*(p+offsetof(node_t,c)));
  return 1;  
}
/*
output:
size = 8
node.c = 33;
*/


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部