background
When I was solving a dynamic programming problem in leetcode, I used a
statement like dp[m][n]={0}
to initialize the array but sometimes it failed to set the array to all zeros which led to the wrong answer.
solution
However, after I changed the code to memset(dp,0,sizeof(dp))
, the dp array was initialized successfully.
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
unsigned long dp[m][n];//
//unsigned long dp[m][n] = {0}; // failed when printed out
memset(dp,0,sizeof(dp)); // success
//....
}
}
my question
I was thinking that the issue was due to that the array size is dynamical. That means the way I initialized the 2d dynamic array is wrong. Should use pointer or vector to initialize such dynamic-size 2d array.
But what bothered me is that from another point of view, 2d array was a local variable which stored in the stack. That means the space it used will be free when the function return.
In this way, each time the 2d array will get some brand new space with all zeros using dp[m][n] ={0}
. Unfortunately, the result proved I was wrong and I have to use memset()
to ensure array was intialized all zeros.
So I wonder someone could give me some help on this C++ thing.