问题描述
我有一个复数数组,我只想在两个元素之间交换.但是,我想实现未知类型的交换(使用 void*).所以我写了下面的代码,使用我看到的第一个交换实现 此处:
I have an array of complex numbers, and I just want to swap between two elements. However, I want to implement the swap for unknown types (using void*). So I wrote the following code, using the first swap implementation that I saw here:
#include<stdio.h>
typedef struct complex complex;
struct complex {
int real;
int img;
};
void swap(void *arr[], int i, int j)
{
void *temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void printComplexArray(complex* cArr, size_t len)
{
int i;
for (i = 0; i < len; i++)
{
printf("Cell %d : real- %d , img- %d\n", i, cArr[i].real, cArr[i].img);
}
}
void main(void)
{
complex cArr[] = { { 22, 3 },{ 1, 13 },{ 5, 7 },{ 8, 4 } };
size_t cLen = (sizeof(cArr) / sizeof(cArr[0]));
swap(cArr, 1, 2);
printComplexArray(cArr, cLen);
}
我希望得到:
Cell 0 : real- 22 , img- 3
Cell 1 : real- 5 , img- 7
Cell 2 : real- 1 , img- 13
Cell 3 : real- 8 , img- 4
但我得到了:
Cell 0 : real- 22 , img- 1
Cell 1 : real- 3 , img- 13
Cell 2 : real- 5 , img- 7
Cell 3 : real- 8 , img- 4
如您所见,不仅交换没有正确执行 - 某些数组元素的内容也发生了变化.你能解释一下原因吗,我该如何解决这个问题?
As you can see, not only that the swapping wasn't performed correctly- the content of some array elements was changed. Can you explain why, and how can I fix this?
推荐答案
你可能想要这个:
void swap(struct complex arr[], int i, int j)
{
struct complex temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
您的解决方案交换了指针,但您的数组不包含指针而是struct complex
s.这基本上就是编译器警告告诉你的.
Your solution swaps pointers but your array doesn't contain pointers but struct complex
s. That's basically what the compiler warning told you.
如果你真的想交换未知类型,你需要这个:
If you really want to swap unknown types, you need this:
void swap(void *arr, int i, int j, size_t size)
{
char temp[size];
char *a = (char*)arr;
memcpy(temp, (a + size * i), size);
memcpy((a + size * i), (a + size * j), size);
memcpy((a + size * j), temp, size);
}
...
swap(cArr, 1, 2, sizeof(*cArr));
size 参数是必须的,因为如果类型未知,则类型的大小当然也是未知的,因此您需要指定大小.
The size parameter is necessary because if the type is unknown, the size of the type is of course unknown too and therefore you need to specify the size.
对于memcpy
,您需要包含,因此您必须编写自己的
memcpy
,因为您可以仅包括 .
For memcpy
you need to include <memory.h>
, so you must write your own memcpy
, as you are allowed to include only <stdio.h>
.
有些编译器不允许 char temp[size];
所以你可以使用 char temp[MAX_SIZE];
定义了 MAX_SIZE
到未知类型的最大预期大小.
Some compilers won't allow char temp[size];
so you just can use char temp[MAX_SIZE];
with MAX_SIZE
defined to the maximum expected size for your unknown types.
这篇关于在 void* 数组上交换无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!