gpt4 book ai didi

c - 通过多级调用传递 c 指针

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:25 25 4
gpt4 key购买 nike

我正在处理类作业(这就是为什么只显示相关代码的原因)。我已将一个指针数组分配给一个随机数数组,并且必须使用冒泡排序技术。

数组设置如下:

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]”但是列表排序的是原始数组而不是指向的数组(这是预料之中的)。

非常感谢任何帮助,
~乔伊

最佳答案

通话中:

pointerSwap(toStore[j],toStore[j+1]);

您正在将 int(toStore[j] 等同于 *(toStore + j))传递给需要一个函数的函数指针。您需要传递一个指针,即:

pointerSwap(toStore + j, toStore + j + 1);

第二个问题是关于错位排序。您的功能签名不允许其他任何内容:

void bubbleSort (int *toStore)

您没有返回任何内容,也没有提供对第二个数组的引用,因此您只能原地排序。如果你真的需要一个单独的数组,你可以这样做:

int *bubbleSort (int *input) {
int* toStore = malloc(DATASIZE * sizeof(int));
memcpy(toStore, input, DATASIZE);
...
//sort toStore
...
return toStore
}

这将返回一个已排序的数组,并且不会触及原始数组。

关于c - 通过多级调用传递 c 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42449250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com