【C/C++】如何不使用 sizeof 求数据类型占用的字节数

实现代码:

c 复制代码
#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 的下一个同数据类型的第一个字节的地址,它们之差即为该数据类型所占的字节数。

相关推荐
带土12 小时前
6. C语言 共用体及typedef
c语言
-Excalibur-3 小时前
形象解释关于TCP/IP模型——层层封装MAC数据帧的过程
linux·c语言·网络·笔记·单片机·网络协议·tcp/ip
想唱rap4 小时前
C++ list 类的使用
c语言·开发语言·数据结构·c++·笔记·算法·list
是苏浙7 小时前
零基础入门C语言之深入了解指针3
c语言·开发语言
侯小啾7 小时前
【09】C语言中的格式输入函数scanf()详解
c语言·开发语言
hope_wisdom9 小时前
C/C++数据结构之用链表实现栈
c语言·数据结构·c++·链表·
GilgameshJSS10 小时前
STM32H743-ARM例程30-Modbus
c语言·arm开发·stm32·单片机·嵌入式硬件
散峰而望10 小时前
基本魔法语言分支和循环 (二) (C语言)
c语言·开发语言·github·visual studio
草莓工作室10 小时前
mbedtls哈希值计算
c语言·哈希算法·mbedtls
橘颂TA11 小时前
【QSS】软件界面的美工操作——Qt 界面优化
开发语言·qt·c/c++·界面设计