简体   繁体   English

为什么++运算符在我的递归方法中导致堆栈溢出,而+1却没有?

[英]Why does the ++ operator cause a stack overflow in my recursive method yet +1 does not?

So I just took a CS test at school tonight and I had to write a recursive method that found the max value in an array. 因此,我今晚才在学校参加了CS测试,我不得不写一个递归方法来在数组中找到最大值。

This is what I came up with: 这是我想出的:

public static int getMax(int[] a, int max, int index)
    {
        if(index == a.length)
        {
            return max;
        }
        if(a[index] > max)
        {
            max = a[index];
        }
        return getMax(a, max, index++);
    }

That's what I put on the paper I turned in, but lo and behold I get home and put it in my IDE to try it out and see if it works and I get a stack overflow. 那就是我在上交的纸上放的东西,但是瞧瞧我回到家并将其放在我的IDE中进行尝试,看看它是否有效,并且我得到了堆栈溢出的信息。 So I do some testing and finally change the second return to: 因此,我做了一些测试,最后将第二个返回值更改为:

return getMax(a, max, index+1);

and no more stack overflow. 并且没有更多的堆栈溢出。

Why does the ++ operator break the method? 为什么++运算符会破坏该方法?

Thanks 谢谢

++ in suffix form increments after the variable is evaluated. 在评估变量 ,后缀形式的++递增。 You're passing the current value of the index into your recursive call, then incrementing it locally back in the parent function. 您正在将索引的当前值传递到递归调用中,然后在父函数中本地将其递增。 In other words, you keep passing the same index value into deeper and deeper recursive calls until you run out of stack. 换句话说,您一直将相同的索引值传递给越来越多的递归调用,直到用完堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这个对象导致堆栈溢出? - why does this object cause a stack overflow? 为什么此方法会导致无限递归调用? - Why does this method cause an Infinite Recursive call? 为什么我的代码会导致Java中的堆栈溢出错误? 它最终应终止。 for循环版本不会导致错误 - Why does my code cause stack overflow error in java? It should terminate eventually. The for loop version does not cause the error 为什么此代码会导致堆栈溢出? 为什么只将== 1更改为&lt;2,然后起作用? - Why does this code cause a stack overflow? And why just change ==1 to <2, and then it works? 为什么 Java 中的这个循环会导致堆栈溢出错误? - Why does this loop in Java cause a stack overflow error? 为什么这种二分搜索实现会导致 Ruby 中的堆栈溢出,但不会导致 Java 中的堆栈溢出? - Why does this binary search implementation cause stack overflow in Ruby but not Java? 为什么编译此代码会导致编译器堆栈溢出? - Why does compiling this code cause a compiler stack overflow? 递归方法和堆栈溢出 - Recursive method and stack overflow 为什么我的Quicksort实现会导致堆栈溢出? - Why does my Quicksort implementation give stack overflow? 为什么我的递归不会返回但最终会出现堆栈溢出? - Why does my recursion not return but end up in a stack overflow?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM