简体   繁体   中英

Stack Overflow Error From Recursive Function

#include<iostream>
#include<string>
#include<sstream>
#include<conio.h>
#include<vector>
#define MAX 100
using namespace std;
int size;

int getlargest(int arr[ ]){
    static int max = -1000;
    static int i = 0;
    if(i < size){
        if(arr[i] >= max){
            max = arr[i];
            i++;
        }
        getlargest(arr);
    }
    return max; 
}

int main(){

    int res;
    cout << "enter the size please: ";
    cin >> size;
    int arr[MAX];

    for(int i=0;i<size;i++){
        cin >> arr[i];
    }
    res = getlargest(arr);
    cout << res;
    getch();
    return 0;
}

I am not experienced with the concept of recursive functions. This code was written to find the maximum element of an array. However, I am getting a stack overflow error. Could anyone correct it? Also, I don't know exactly where to insert recursion.

You have several problems, all of them small.

First, you make no progression through the array: you always call with the same argument, that being the entire array. The strategy of recursion is to do something simple, and then reduce the problem to something smaller when you call again.

In this case, you have the concept right: check one element against the largest of the rest of the list. You do recur to find the maximum, but you don't reduce the list. You also don't actually work well with the list max. For instance, note that (on each call) you're returning the max to the previous level ... but you don't save it at all.

Try this instead:

  • take the first element off the list;
  • find the max of the remainder;
  • return the larger of those two.

The code might look like this:

if(arr.size() == 1) {
    return arr[0]
else {
    max = getlargest(++arr);
    if (arr[0] >= max)
        max = arr[0]
}
return max;

Note the little C trick here: ++arr increments arr , as an array reference, to the next element. You may have seen this already as a character pointer and string variable.

Well, it seems you're trying to do something that is easier to do with a loop than recursion. You can implement getlargest() like this:

int getlargest(int arr[]) {
    int max = arr[0]; // This is safer than initializing max with 0. What if arr[0] is the largest element and all elements are below 0?
    for (int i = 0; i < size; ++i)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

I am not experienced with the concept of recursive functions.

Assuming you want to learn how to use recursion, you should take a look at factorial . It's a no-brainer to find the factorial of an integer i using a recursive function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM