我正在尝试使用数组指针进行选择排序。
void sort(int size, int *ptr)
{
int temp;
bool swap;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (*ptr[count] > *ptr[count + 1])
{
temp = *ptr[count];
*ptr[count] = *ptr[count + 1];
*ptr[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
我收到很多错误说非法方向,因为在使用 * 时它必须是一个指针。我在其他方法中使用它很好,只是这个方法有问题。这是我正在使用的调用。
sort(arraySize, numArray);
一切都在其他方法中声明和工作。
最佳答案
使用 ptr[]
而不是 *ptr[]
因为,
ptr
是指针,如果与 []
一起使用,它会像数组一样返回该位置的元素。
void sort(int size, int *ptr)
{
int temp;
bool swap;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (ptr[count] > ptr[count + 1])
{
temp = ptr[count];
ptr[count] = ptr[count + 1];
ptr[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
关于c++ - 使用指针进行选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28424462/