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

Joh*_*nny 0 c memory variables recursion

我写了一个程序来查找数组中最大的数字.问题是,每次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
    }
}
Run Code Online (Sandbox Code Playgroud)

程序返回零作为最大整数.有任何想法吗?

Car*_*rum 6

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

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

largest永远0.

你可以制作largest 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 它可能不是 - 调试器工件或OP可能是误读.无论如何,OP的问题是"该程序将零返回为最大整数.任何想法?" (2认同)