gpt4 book ai didi

C 通过引用传递

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

在我的 lSearch 函数(线性搜索)中,我试图通过引用传递一个名为 *numComparisons 的变量。

每次进行比较时,它都应该递增,但由于某种原因它没有这样做。为什么不?当它到达 main.. 的末尾时,该函数确实起作用(因为它会找到一个比较,或者如果没有找到比较,它将返回 -1)但是 numComparisons 值每次都输出为 0。

int lSearch(int arr[], int size, int target, int *numComparisons)
{
int counter;

for(counter = 0; counter < size; counter++)
{
*numComparisons++;

if(arr[counter] == target)
return(*numComparisons);
}
return(-1);
}


int main(int argc, char * argv[])
{
int enterNumbers[1000], copy[1000], counter;
int numComparisons = 0, target = 26;

printf("Enter in numbers and press -999 when you are done: ");

for(counter = 0;; counter++)
{
scanf("%d", &enterNumbers[counter]);

if(enterNumbers[counter] == -999)
break;
}

arrayCopy(enterNumbers, copy, counter);
sort(copy, counter);

if(lSearch(copy, counter, target, &numComparisons) >=0)
{
printf("Target number found in linear search.\n");
printf("Number of comparisons: %d\n", numComparisons);
}
else
{
printf("Target number was not found in the linear search\n");
printf("Number of comparisons: %d\n", numComparisons);
}
return 0;

最佳答案

改变

    *numComparisons++;

    (*numComparisons)++;

后缀递增的优先级高于解引用运算符,因此您的代码递增指针而不是递增指向的值。

关于C 通过引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538311/

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