交换void*数组无法正常工作

Rod*_*igo -2 c arrays void-pointers

我有一个复数的数组,我只想在两个元素之间交换.但是,我想实现未知类型的交换(使用void*).所以我使用我在这里看到的第一个交换实现编写了以下代码:

#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);
}
Run Code Online (Sandbox Code Playgroud)

我期望得到:

Cell 0 : real- 22 , img- 3
Cell 1 : real- 5 , img- 7
Cell 2 : real- 1 , img- 13
Cell 3 : real- 8 , img- 4
Run Code Online (Sandbox Code Playgroud)

但我得到了:

Cell 0 : real- 22 , img- 1
Cell 1 : real- 3 , img- 13
Cell 2 : real- 5 , img- 7
Cell 3 : real- 8 , img- 4                     
Run Code Online (Sandbox Code Playgroud)

如您所见,不仅交换未正确执行 - 某些数组元素的内容也发生了变化.你能解释一下原因,我该如何解决这个问题?

Jab*_*cky 5

你可能想要这个:

void swap(struct complex arr[], int i, int j)
{
    struct complex temp;
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
Run Code Online (Sandbox Code Playgroud)

您的解决方案交换指针,但您的数组不包含指针,但struct complexs.这基本上是编译器警告告诉你的.

如果你真的想要交换未知类型,你需要这个:

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));
Run Code Online (Sandbox Code Playgroud)

size参数是必需的,因为如果类型未知,则类型的大小当然也是未知的,因此您需要指定大小.

因为memcpy您需要包含<memory.h>,所以您必须自己编写memcpy,因为您只能包含<stdio.h>.

一些编译器不会允许char temp[size];这样你才可以使用char temp[MAX_SIZE];MAX_SIZE定义的最大预期大小为您的未知类型.