根据结构体里面元素的某个地址计算机构体地址

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

#define CONTAINER_OF(ptr, type, member)((type *)((char *)ptr - (char *)&((type*)0)->member))
#define ARRAY_SIZE(a)(sizeof(a) / sizeof((a)[0]))

struct user_data
{
     char a;
     char b;
     int c;
};

int main(int argc, char *argv[])
{
      struct user_data *tmp;
      char *h;
      struct user_data = (struct user_data *)malloc (sizeof(struct user_data));
if(p_data ==NULL)
{
      printf("no memory!\n");
      return -1;
}

     h = &p_data->b;

     printf("p_data's address is 0x%p\n", p_data);
     printf("h's           address is 0x%p\n", h);

     tmp = CONTAINER_OF(h, struct user_data, b);
     printf("tmp's address is 0x%p\n", tmp);


     return 0;
}

你可能感兴趣的:(计算机)