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

相关推荐
小莞尔1 天前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔1 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing102329291 天前
Day03_刷题niuke20250915
c语言
第七序章1 天前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
l1t2 天前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb
l1t2 天前
利用美团龙猫用libxml2编写XML转CSV文件C程序
xml·c语言·libxml2·解析器
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长2 天前
C语言---循环结构
c语言·开发语言·算法
程序猿编码2 天前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备
mark-puls2 天前
C语言打印爱心
c语言·开发语言·算法