我编写了一个程序来查找数组中的最大数。问题是每次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
}
}
程序返回零作为最大整数。有任何想法吗?