实现 sizeof
思路: 用指针表示地址,然后相减
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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