0

For example in this code, which works fine, memoization done with an array not a pointer to an array. (int mem[] instead of int* mem)

int fibonacci(int n,int mem[]){
    if(n < 3)
    return 1;   

    if(mem[n])
    return mem[n];

    mem[n] = fibonacci(n - 1, mem) + fibonacci(n - 2, mem);
    return mem[n];
    } 

int climbStairs(int n){
    int mem[50] = {0};
    return fibonacci(n + 1, mem);
}

I don't see how, when one of the functions returns, how can the caller function of the returned function have the data to previous mem[n]. Isn't the functions array supposed to be deleted when the function returned? How can after that function returned, another function that a caller function calls can have that value?

Note: This is a solution to Climbing Stairs in leetcode. Written by me.

1 Answers1

0

When using [] in a function argument, it is a pointer.

int foo(int x[])

and

int foo(int *x)

are 100% equivalent.

However, this would be something else:

int foo(int x[10])
klutt
  • 30,332
  • 17
  • 55
  • 95