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

相关推荐
RuoZoe1 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_4 天前
C语言内存函数
c语言·后端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874756 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237176 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish6 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人6 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J6 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹46 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow6 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法