首页 > 解决方案 > 如何正确交换 void 指针?

问题描述

我有一个任务:我需要通过“基于空指针的”交换函数交换
数组中的元素。它是一个简单的冒泡排序算法。 但是我的功能不起作用!我的意思是它调用正确,但什么也没做。我的预排序数组没有改变。这里可能有什么问题以及如何解决?
void SwapInt(void *x, void *y)

void SwapInt(void *x, void *y)
{
    void *buffer = x;
    x = y;
    y = buffer;
}

bool CmpInt(void *x, void *y)
{
    int *intPtrX = static_cast<int*>(x);
    int *intPtrY = static_cast<int*>(y);
    if(*intPtrX > *intPtrY)
        return true;
    else
        return false;
}

void Sort(int array[], int nTotal, size_t size, void (*ptrSwapInt)(void *x, void *y), bool (*ptrCmpInt)(void *x, void *y))
{
    for (int i = 0; i < nTotal; i++)
    {
        for (int j = 0; j < nTotal - 1; j++)
        {
          if (ptrCmpInt(&array[j] , &array[j + 1]))
          {
            ptrSwapInt(&array[j], &array[j + 1]);
          }
        }
    }
}

PS 我已经访问过StackOverflow_1StackOverflow_2,但我仍然不知道有什么问题。

标签: c++

解决方案


您不能通过交换指针来交换整数,您必须取消引用指针。为此,您必须将它们转换为它们真正的 int 指针。

void SwapInt(void *x, void *y)
{
    int temp = *static_cast<int*>(x);
    *static_cast<int*>(x) = *static_cast<int*>(y);
    *static_cast<int*>(y) = temp;
}

事实上,你在你的CmpInt函数中完美地做到了这一点,所以我不确定问题出在哪里SwapInt


推荐阅读