c++ - 如何正确交换 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_1和StackOverflow_2,但我仍然不知道有什么问题。
解决方案
您不能通过交换指针来交换整数,您必须取消引用指针。为此,您必须将它们转换为它们真正的 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
。
推荐阅读
- devops - 是否有适用于 Tibco Business Works 的编程 API
- flask - 如何为 Authlib 使用多个范围
- vue.js - Vue 路由器重置全局数据
- azure - 长期备份保留列表不可用
- vba - 提取并列出匹配的单元格
- spring-boot - 非常困惑:spring-boot-starter-web 是否需要将 Spring Boot 与 gRPC 一起使用
- python - 使用夹具和命令行参数参数化 pytest 测试
- osmdroid - 使用 OSMDroid Tilesource 在本地绘制瓷砖
- php - 带小数的树枝范围
- html-table - 如何自定义 Material-ui 表格行列(粘滞)