我已經與易C題++程序,發現在給定的矩陣的最大子矩陣:C++意外的內存錯誤
int *A = new int[n*m];
... setting fields for matrix, finding the largest one and etc
... r := size of square-submatrix, max_i := row, max_j := column of the largest
for (i = max_i; i < max_i + r; i++)
{
for (j = max_j; j < max_j + r; j++)
cout << A[i * n + j] << "\t";
cout << "\n";
}
<memory free>
end of program
一切的偉大工程(所以這不是問題的邏輯) - 找到正確的子矩陣,prinitng等。當我把內存中的空行刪除時,意外地(或由於深夜)刪除[] A或刪除所有壓縮的內容(但它仍然正確地打印結果 - 所以錯誤必須在這一行中)。我試過把它設置爲NULL和每個組合。出了什麼問題?
在此先感謝
編輯:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i,j,k;
int m,n;
int r;
cout << "Size of matrix: \nRows: ";
cin >> n;
cout << "Columns: ";
cin >> m;
int *A = new int[n*m];
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
A[n*i + j] = rand() % 19 - 9;
cout << A[n*i + j] << "\t";
}
cout << "\n";
}
cout << "Size of submatrix: ";
cin >> r;
int liczba_kwadratow = (m + 1 -r) * (n+1 -r);
int max = -10000;
int max_i = 0;
int max_j = 0;
int row_iter = 0;
int col_iter = 0;
for (k = 0; k <liczba_kwadratow; k++)
{
int sum = 0;
for (i = row_iter; i < row_iter + r; i++)
for (j = col_iter; j < col_iter + r; j++)
sum += A[i * n + j];
if (sum > max)
{
max = sum;
max_i = row_iter;
max_j = col_iter;
}
col_iter++;
if (row_iter + r > m)
{
row_iter++;
col_iter = 0;
}
}
cout << "Field of the largest submatrix " << r << " of " << r << " equals " << max << "\n";
for (i = max_i; i < max_i + r; i++)
{
for (j = max_j; j < max_j + r; j++)
cout << A[i * n + j] << "\t";
cout << "\n";
}
...works great without delete[] A or delete A
}
有沒有機會給A [-1]寫信? – drescherjm
我不這麼認爲。我已經發布了代碼。謝謝! – lemoid
使用一些'assert'來確保你沒有執行任何out-of-bound訪問,或者更好的方法是使用at()的'std :: vector'和成員函數'執行訪問。這樣,如果你試圖訪問越界,就會拋出一個異常(如果你簡單地使用'std :: vector :: operator []')這個**不是這種情況)。如果你使用這樣的矢量,可以很容易地測試發生了什麼。作爲一般規則,您應該嘗試避免在現代C++中使用原始指針。 – vsoftco