C 语言探究(0)

2023-12-26 13:10:30

泛型指针

? ? 通常情况下,C只允许相同类型的指针之间进?转换。例如:?个
字符型指针sptr(?个字符串)和?个整型指针iptr,我们不允许把sptr
转换为iptr或把iptr转换为sptr。但是,泛型指针能够转换为任何类型的
指针,反之亦然。因此,如果有?个泛型指针gptr,就可以把sptr转换
为gptr或者把gptr转换为sptr。在C语?中,通常声明?个void指针来表
?泛型指针。


泛型指针实例

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>


double cpuSecond() {
	struct timeval tp;
	gettimeofday(&tp,NULL);
	return ((double)tp.tv_sec + (double)tp.tv_usec*1.e-6);
}

void initialData(float *ip,int size) {
	// generate different seed for random number
	//time_t t=NULL;
	//srand((unsigned) time(&t));
	srand((unsigned)time(NULL));
	for (int i=0; i<size; i++) {
		ip[i] = (float)( rand() & 0xFF )/10.0f;
	}
}

void printdata(float *data, int size)
{	
	for(int i=0;i<size;i++){
		printf("%f  ", data[i]);
	}
	
	printf("\n");
}

int swap1(void *x, void *y, int size)
{
	void *tmp;
	if((tmp=malloc(size))==NULL){
		return-1;
	}
	
	memcpy(tmp, x, size);
	memcpy(x, y, size);
	memcpy(y, tmp, size);
	
	free(tmp);
	return 0;
	
}

int swap2(float *x, float *y, int nelem)
{
	float tmp;
	for(int i=0;i<nelem;i++){
		tmp = x[i];
		x[i]=y[i];
		y[i]=tmp;
	}

	return 0;
	
}


int main(void)
{
	float *h_x;
	float *h_y;
	int nElem = 4096;
	
	h_x = (float *)malloc(sizeof(float)*nElem);
	h_y = (float *)malloc(sizeof(float)*nElem);
	
	initialData(h_x, nElem);
	sleep(2);  //avoid to generate the same random data
	initialData(h_y, nElem);
	
	//print 5 data
	printf("1st method\n");
	printf("before swap:\n");
	printf("x value: ");
	printdata(h_x, 5);
	printf("y value: ");
	printdata(h_y, 5);
	
	double istart = cpuSecond();
	swap1(h_x, h_y, nElem*sizeof(float));
	double iend = cpuSecond()-istart;
	
	printf("after swap:\n");
	printf("x value: ");
	printdata(h_x, 5);
	printf("y value: ");
	printdata(h_y, 5);
	printf("time elpased %f sec.\n", iend);
	
	printf("++++++++++++++++++++++++++++++++++++++++\n");
	
	printf("2st method\n");
	printf("before swap:\n");
	printf("x value: ");
	printdata(h_x, 5);
	printf("y value: ");
	printdata(h_y, 5);
	
	istart = cpuSecond();
	swap2(h_x, h_y, nElem);
	iend = cpuSecond()-istart;
	
	printf("after swap:\n");
	printf("x value: ");
	printdata(h_x, 5);
	printf("y value: ");
	printdata(h_y, 5);
	printf("time elpased %f sec.\n", iend);
	
	return 0;
}


运行结果

?从运行时间来看,虽然空指针可以用来表示泛型,可以实现多种数据类型的操作,但是在本例执行的效率并不高

文章来源:https://blog.csdn.net/xuelanga000/article/details/135216129
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。