实现 sizeof

实现 sizeof

思路: 用指针表示地址,然后相减

#include 
#include 
#include 

#define sizeof_v(var)   ((size_t) ((char *)(&(var) + 1) - (char *)&(var)))
#define sizeof_t(type)  ((size_t) ((type *)0 + 1))

typedef struct
{
  int age;
  char name[32];
}STU_T;

int main()
{
  char c;
  int i=123;

  printf("mysizeof(): %d\n",sizeof_v(c));
  printf("mysizeof(): %d\n",sizeof_v(i));
  printf("mysizeof(): %d\n",sizeof_t(char));
  printf("mysizeof(): %d\n",sizeof_t(int));
  printf("mysizeof(): %d\n",sizeof_t(STU_T));
  return 1;
}
[liboyang@database74 test]$ ./a.out 
mysizeof(): 1
mysizeof(): 4
mysizeof(): 1
mysizeof(): 4
mysizeof(): 36

你可能感兴趣的:(C++,sizeof)