gpt4 book ai didi

c - 编写处理任何类型数组的函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:42:29 24 4
gpt4 key购买 nike

我在 C 中遇到了这个问题:

Implement the void arr_mix_x(void *arr, int n, size_t size); function. The function will mix the elements. It will do so by:

  1. Putting the lower half of the array in the even indexes of the array.
  2. Putting the higher half of the array in the odd indexes of the array, reversed.
  3. After doing so, move all elements one left in cycle.

我成功地完成了问题的第一部分,这是相同的,但只处理 int 数组。但是,我编写的代码(或从问题的第一部分修改而来)在我尝试运行时出现了段错误。这是代码:

void arr_mix_x(void *arr, int n, size_t size)
{
int i, j;
void *tmpArr = malloc(size);
void *tmp = NULL;

memcpy(tmpArr, arr, size);

for (i = 0, j = n-1; i < n/2; i++, j--)
{
memcpy(arr+(i*2), tmpArr+i, size/n);
memcpy(arr+((i*2)+1), tmpArr+j, size/n);
}

memcpy(tmp, arr, size/n);

for (i = 0; i < n-1; i++)
{
memcpy(arr+i, arr+i+1, size/n);
}

memcpy(arr+n-1, tmp, size/n);

free(tmpArr);
tmpArr = NULL;
}

这是数组和对函数的调用:

int arr[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

arr_mix_x(arr, 10, sizeof(int) * 10);

最佳答案

好吧,我的代码本身显然有一些错误。我改变了它,它现在可以工作了。以下是代码,如果它可以帮助遇到类似问题的任何人:

void arr_mix_x(void *arr, int n, size_t size)
{
int i, j;
void *tmpArr = malloc(size * n);
void *tmp = malloc(size);

memcpy(tmpArr, arr, size * n);

for (i = 0, j = n-1; i < n/2; i++, j--)
{
memcpy(arr+(i*2*size), tmpArr+(i*size), size);
memcpy(arr+((i*2+1)*size), tmpArr+(j*size), size);
}

memcpy(tmp, arr, size);

for (i = 0; i < n-1; i++)
{
memcpy(arr+(i*size), arr+((i+1)*size), size);
}

memcpy(arr+((n-1)*size), tmp, size);

free(tmpArr);
tmpArr = NULL;

free(tmp);
tmp = NULL;
}

函数调用:

arr_mix_x(arr, 10, sizeof(int));

关于c - 编写处理任何类型数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733717/

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