2016-12-29 63 views
0

我的問題是我們可以使用int a[10][10] = {{0}}初始化二維數組。在C/C++中將兩個二維數組初始化爲零

根據initialize-large-two-dimensional-array-in-c頂端回答,

int array [ROW][COLUMN] = {0};
這意味着:第一行中的「初始化第一個欄爲0,而所有其他項目,如果他們有靜態存儲時間,即將它們設置爲零。「

但是,檢查C99 Standard 9899:TC3C++11 Standard N4296,我還沒有發現任何支持此答案中提到的正式記錄。

此外,當我嘗試解決以下解決方案的LeetCode 474. Ones and Zeroes問題時遇到此問題。

// 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]}; 
    } 
}; 
+0

N4296是C++ 14和C++ 17之間的草稿,而不是您聲稱的「C++ 11標準」。 –

+0

我誤解了你的問題。 – coderredoc

+0

在++ ++ cnts中強制轉換[static_cast (c =='1')];'是多餘的 –

回答

4

您的代碼是C++代碼。關於C的其他問題和文件是不相關的; C和C++是不同的語言。

在標準C++中,編譯時必須知道數組維數。 int dp[m + 1][n + 1]是一個錯誤(更不用說試圖初始化它)。

可能您使用的編譯器提供C++ VLA作爲非標準擴展。在這種情況下,您將受到特定編譯器的支配,以確定代碼的行爲,以及={{0}}的行爲可能是什麼。 C++標準將無濟於事。

我的建議是避免使用非標準結構,以便保留標準文檔提供的保證。

+0

非常感謝你!順便說一句,'static_cast'是不必要的?因爲我認爲它可以避免隱式轉換。 –