实现代码:
#include <stdio.h>#define GET_TYPE_SIZE(TYPE) ((char *)(&TYPE + 1) - (char *) & TYPE)int main(void)
{char a = 'a';short b = 0;int c = 0;long d = 0;long long e = 0;float f = 0.0;double g = 0.0;long double h = 0.0;char* i = NULL;printf("char %lld \r\n", GET_TYPE_SIZE(a));printf("short %lld \r\n", GET_TYPE_SIZE(b));printf("int %lld \r\n", GET_TYPE_SIZE(c));printf("long %lld \r\n", GET_TYPE_SIZE(d));printf("long long %lld \r\n", GET_TYPE_SIZE(e));printf("float %lld \r\n", GET_TYPE_SIZE(f));printf("double %lld \r\n", GET_TYPE_SIZE(g));printf("long double %lld \r\n", GET_TYPE_SIZE(h));printf("char* %lld \r\n", GET_TYPE_SIZE(i));return 0;
}
输出:
- 运行环境:Visual Studio 2022 ×64
原理:(char *)&TYPE 返回 TYPE 第一个字节的地址,(char *)(&TYPE + 1) 返回 TYPE 的下一个同数据类型的第一个字节的地址,它们之差即为该数据类型所占的字节数。