gpt4 book ai didi

c - 在 C 中交换没有 memcpy 的 void* 指针数组的项目

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:21 24 4
gpt4 key购买 nike

我正在写一些学校项目,我需要交换两个 void* 指针数组。我可以用类似下面的代码来做到这一点:

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。这可能吗?

谢谢

最佳答案

为什么不这样交换呢?:

void swap(void *v[], int i, int j)
{
void *temp;

temp = v[i];
v[i] = v[j];
v[j] = temp;
}

正如 qsort 所做的那样(交换数组中的元素):

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 - 在 C 中交换没有 memcpy 的 void* 指针数组的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16543052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com