函数指针实现无类型打印

本文介绍了一种使用C语言打印不同类型内存数据的方法。通过定义通用的打印函数,并根据输入数据类型选择适当的处理方式(整数或浮点数),实现了灵活且高效的数据展示。此方法有助于理解内存布局及数据解析。
#include<stdio.h>
void MyInt(void const *ar,int size)
{
	size/=4;		//int		一次打印4字节
	int const *p=(int const *)ar;
	for(int i=0;i<size;++i)
	{
		printf("%d ",p[i]);
	}
	printf("\n");
}
void MyFloat(void const *ar,int size)
{
	size/=4;	//float		一次打印4字节
	float const *p=(float const*)ar;
	for(int i=0;i<size;++i)
	{
		printf("%f ",p[i]);
	}
	printf("\n");
}
void MyPrint(void const *ar,int size,void(*pfun)(void const*,int))
{
	if(NULL!=pfun)
	{	
		pfun(ar,size);
	}

}
void main()
{
	const int n=10;
	int ar[n]={12,23,34,45,56,67,78,89,90,100};
	float dr[n]={1.2,2.3,3.4,4.5,6.7,8.9,9.0,10.0};
	MyPrint(ar,sizeof(ar),MyInt);
	MyPrint(dr,sizeof(dr),MyFloat);
}
//sizeof中数组名代表整个数组的大小,其他情况下数组名代表首元素的地址。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值