gpt4 book ai didi

c - 为什么我的变量在我的 C 程序中递归调用时改变值?

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

我编写了一个程序来查找数组中的最大值。问题是每次递归调用 find_largest 函数时,largest 变量似乎都被内存中其他地方的垃圾填满了。我已经使用调试器逐步完成它,并且在递归调用之前它似乎工作正常。数组的指针和对 largest 的更新(如果适用)显示预期值。

/*This program will find the largest integer in an array. It was written to practice
using recursion.*/

#include <stdio.h>
void find_largest(int *a, int n);
int main() {
int a[] = {10, 27, 101, -8, 16, 93};
int n = 6, i = 0;
printf("Current array: ");
while(i < n) {//print array
printf("%d ", a[i]);
i++;
}
find_largest(a, n);
return 0;
}//end main

//This function will start at the last element, and then step through the array
//in reverse order using pointers.
void find_largest(int *a, int n) { //formulate the size-n problem.
int largest = 0;
if(n == 0) { //find the stopping condition and the corresponding return
printf("\nThe largest number is: %d \n", largest);
}
else { //formulate the size-m problem.
n--; //decrement so that the proper number is added to pointer reference
if(largest <= *(a + n)) //check if element is larger
largest = *(a + n); //if larger, assign to largest
find_largest(a, n); //recursive call
}
}

程序返回零作为最大整数。有什么想法吗?

最佳答案

largest 并非由所有递归调用共享,每个递归调用都有自己的副本。这意味着在基本情况下,您执行以下代码:

int largest = 0;
if (n == 0) {
printf("\nThe largest number is: %d \n", largest);
}

largest始终 0

您可以将 largest static 设置为 static 并且它会起作用,尽管它的实现方式有点奇怪。我更愿意做这样的事情:

int find_largest(int *a, int n)
{
int subproblem;

// base case - single element array, just return that element
if (n == 1)
{
return *a;
}

// recursion - find the largest number in the rest of the array (increase
// array pointer by one, decrease length by one)
subproblem = find_largest(a + 1, n - 1);

// if the current element is greater than the result of the subproblem,
// the current element is the largest we've found so far - return it.
if (*a > subproblem)
return *a;

// otherwise, return the result of the subproblem
else
return subproblem;
}

关于c - 为什么我的变量在我的 C 程序中递归调用时改变值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17079366/

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