当我们重复调用递归函数时,局部变量只获取内存或者每次都在Java?
when we call recursive function repeatedly the local variables get memory only ones or every time in Java?
int fact(int n){
int result;
if(n==1) return 1;
result=fact(n-1)*n;
return result;
}
所以,如果我调用 fact(3) ,每次调用 result 变量将在堆栈中获得单独的内存?
(对不起,如果这是一个愚蠢的问题,但我似乎无法理解这个概念。)
是的。但是在这种情况下你不需要使用变量:
int fact(int n){
if (n==1)
return 1;
return fact(n-1)*n;
}
每个方法调用都会占用 space 内存。
How memory is allocated to different function calls in recursion?
When any function is called from main(), the memory is allocated to it on
the stack. A recursive function calls itself, the memory for the called
function is allocated on top of memory allocated to calling function and
different copy of local variables is created for each function call. When
the base case is reached, the function returns its value to the function
by whom it is called and memory is de-allocated and the process continues.
递归方法与任何其他方法相同。每次调用递归方法(从另一个方法或在其自身内部)时,它都会推入堆栈中的单独内存,然后在 returns.
时弹出。
int fact(int n){
int result;
if(n==1) return 1;
result=fact(n-1)*n;
return result;
}
所以,如果我调用 fact(3) ,每次调用 result 变量将在堆栈中获得单独的内存?
(对不起,如果这是一个愚蠢的问题,但我似乎无法理解这个概念。)
是的。但是在这种情况下你不需要使用变量:
int fact(int n){
if (n==1)
return 1;
return fact(n-1)*n;
}
每个方法调用都会占用 space 内存。
How memory is allocated to different function calls in recursion?
When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for the called function is allocated on top of memory allocated to calling function and different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues.
递归方法与任何其他方法相同。每次调用递归方法(从另一个方法或在其自身内部)时,它都会推入堆栈中的单独内存,然后在 returns.
时弹出。