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

相关推荐
dllxhcjla38 分钟前
07 标识符命名规则
c语言
杨福瑞2 小时前
C语言数据结构:算法复杂度(2)
c语言·开发语言·数据结构
DuHz2 小时前
C程序中的循环语句
c语言·嵌入式硬件·软件工程
一念&2 小时前
每日一个C语言知识:C 指针
c语言·开发语言
deng-c-f4 小时前
Linux C/C++ 学习日记(22):Reactor模式(二):实现简易的webserver(响应http请求)
linux·c语言·网络编程·reactor·http_server
朱嘉鼎7 小时前
C语言之可变参函数
c语言·开发语言
你好,我叫C小白11 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
朱嘉鼎13 小时前
状态机的介绍
c语言·单片机
Neverfadeaway14 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
一碗绿豆汤14 小时前
c语言-流程控制语句
c语言