探测数据类型存储空间大小
作者:jafon.tian
转载请注明出处:https://blog.csdn.net/JT_Notes
在C语言编程得时候,经常需要知道程序编译器对各种数据类型分配的存储空间大小,进而进行精确的内存操作。下面给出一种探测方法,
核心宏定义
#define PRINT_SIZE(type) do{ \
printf("sizeof(" #type ")=%d\n", sizeof(type)); \
}while(0)
使用示例
// typesize.c
#include <stdio.h>
#define PRINT_SIZE(type) do{ \
printf("sizeof(" #type ")=%d\n", sizeof(type)); \
}while(0)
int main(int argc, char* argv[])
{
PRINT_SIZE(char);
PRINT_SIZE(unsigned char);
PRINT_SIZE(short);
PRINT_SIZE(unsigned short);
PRINT_SIZE(int);
PRINT_SIZE(unsigned int);
PRINT_SIZE(long);
PRINT_SIZE(float);
PRINT_SIZE(double);
return 0;
}
编译并测试
$ gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ cat /proc/version
Linux version 3.10.0-327.22.2.el7.x86_64 (builder@kbuilder.dev.centos.org) (gcc version 4.8.3 20140911 (Red Hat 4.8.3-9) (GCC) ) #1 SMP Thu Jun 23 17:05:11 UTC 2016
$ gcc typesize.c && ./a.out
sizeof(char)=1
sizeof(unsigned char)=1
sizeof(short)=2
sizeof(unsigned short)=2
sizeof(int)=4
sizeof(unsigned int)=4
sizeof(long)=8
sizeof(float)=4
sizeof(double)=8