jeudi 29 décembre 2016

Initialize two 2-d array to zero in C/C++

My question is can we initialize 2-d array using int a[10][10] = 0.

According to the top answer in initialize-large-two-dimensional-array-in-c,

int array [ROW][COLUMN] = {0};
which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."

However, checking C99 Standard 9899:TC3 and C++11 Standard N4296, I haven't found any official records supporting what was mentioned in this answer.

Besides, I do come across this issue when I try to solve the LeetCode 474. Ones and Zeroes problem with the following solution.

// To make question clear:
// It seems that "int dp[m + 1][n + 1] = 0" cannot initilize all elem to 0
// "memset(dp, 0, sizeof dp)" is necessary to pass the OJ test. Any idea?

class Solution {
 public:
  // m : 0s, n : 1s
  int findMaxForm(vector<string>& strs, int m, int n) {
    int dp[m + 1][n + 1] = 0;
    // We will get "Wrong Answer" without memset() function below
    memset(dp, 0, sizeof dp);
    for (auto& str : strs) {
      auto cost = getCost(str);
      for (int i = 0; i + cost.first <= m; ++i)
        for (int j = 0; j + cost.second <= n; ++j)
          dp[i][j] = std::max(dp[i + cost.first][j + cost.second] + 1,
              dp[i][j]);
    }
    int max = 0;
    for (int i = 0; i <= m; ++i)
      for (int j = 0; j <= n; ++j)
        max = std::max(max, dp[i][j]);
    return max;
  }

 private:
  pair<int, int> getCost(const string& str) const {
    int cnts[] = {0, 0};
    for (char c : str) ++cnts[static_cast<char>(c == '1')];
    return {cnts[0], cnts[1]};
  }
};

Aucun commentaire:

Enregistrer un commentaire