在C中交换没有memcpy的void *指针数组的项 [英] Swap items of void* pointer array without memcpy in C
本文介绍了在C中交换没有memcpy的void *指针数组的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一些学校项目,并且需要交换两项void *指针数组.我可以使用以下代码来做到这一点:
I am writing some school project, and I need to swap two items of void* pointer array. I can do this with something like following code:
void swap(void *base, int len, int width)
{
void *p = malloc(width);
memcpy(p,base,width);
memcpy(base,(char*)base+width,width);
memcpy((char*)base+width,p,width);
free(p);
}
但是我需要不使用memcpy交换项目,仅使用malloc,realloc和free.那有可能吗?
But I need to swap items WITHOUT memcpy, only with malloc, realloc and free. Is that even possible?
谢谢
推荐答案
为什么不以这种方式交换?:
Why don't swap in this way?:
void swap(void *v[], int i, int j)
{
void *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
与qsort一样(在数组中交换元素):
As qsort does (swaps elements within the array):
void sort(void *v[], int left, int right, int (*comp)(const void *, const void *))
{
int i, last;
if (left >= right) return;
swap(v, left, (left + right) / 2);
last = left;
for (i = left + 1; i <= right; i++) {
if ((*comp)(v[i], v[left]) < 0)
swap(v, ++last, i);
}
swap(v, left, last);
sort(v, left, last - 1, comp);
sort(v, last + 1, right, comp);
}
这篇关于在C中交换没有memcpy的void *指针数组的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文