【发布时间】:2017-02-24 22:19:29
【问题描述】:
我正在做一个班级作业(这就是为什么只显示相关代码的原因)。我已经分配了一个指向随机数数组的指针数组,并且必须使用冒泡排序技术。
数组设置如下:
int array[DATASIZE] = {71, 1899, 272, 1694, 1697, 296, 722, 12, 2726, 1899};
int *arrayPointers = array; // donation array
函数调用来自main,看起来如下:
bubbleSort(arrayPointers);
我必须在一个单独的函数中交换指针:
void pointerSwap( int *a , int *b)
{
// swap the pointers and store in a temp
int temp = *a; // temp storage of pointer a while being reassigned
*a = *b;
*b = temp;
}// end of pointerSwap
来自实际的冒泡排序:
void bubbleSort (int *toStore)
{
//sort each of the pointers successively
int i,j; // counters
for (i=DATASIZE-1;i>1;i--)
{
for (j=0;j<DATASIZE-1;j++)
{
if (toStore[j]>toStore[j+1])
{
pointerSwap(toStore[j],toStore[j+1]);
}// end of if?
}// end of j for loop
}// end of i for loop
}// end of buubleSort
我的问题是,当我尝试编译代码时,调用指针交换时出现以下错误:
传递“pointerSwap”的参数 1 使指针从整数而不进行强制转换
注意:预期为“int *”,但参数为“int”类型
传递“pointerSwap”的参数 2 使指针来自整数而不进行强制转换
注意:预期为“int *”,但参数的类型为“int”
我不确定我做错了什么,我尝试了“&toStore[j]”和“&toStore[j+1]”,但是列表对原始数组而不是指向数组进行排序(这是意料之中的)。
非常感谢任何帮助,
~乔伊
【问题讨论】:
-
但是您在哪里定义了另一个存储位置以避免就地排序?注意:
toStore+j的指针更清晰。 -
外部 for 循环中的 j 是怎么回事?那不应该是我吗?
-
因为你有一个函数
void bubbleSort (int *toStore),它只接受一个参数并且不返回任何东西,除了对传递的数组进行排序之外,该函数还能做什么呢?如果您不想更改原始数组,则必须在某个地方复制它。请提供您拨打bubbleSort的代码。 -
pointerSwap 是否应该交换指针或交换指针指向的值?在它交换值的那一刻,顾名思义它应该交换指针
-
它应该交换指针,以便原始列表保持不变
标签: c arrays pointers bubble-sort