0
我的代碼編譯,但會引發以下異常:C/C++:「試圖讀取或寫入保護內存」異常
An unhandled exception of type 'System, Access Violation Exception' occured Additional Information: Attempted to read or write protected memory. . .
的錯誤與s=s+a[z][r]*b[f][h]
這裏的副本代碼:
#include"stdafx.h"
#include"iostream"
using namespace std;
int main()
{
int **a, **b;
int z, r, f, h, a_r, a_c, b_r, b_c, s = 0;
cout << "Enter the size of the matrix(nxm) :" << endl;
cin >> a_r >> a_c;
cout << "enter the size of the mask :" << endl;
cin >> b_r >> b_c;
a = (int **) malloc(10 * a_r);
for (int i = 0; i < a_c; i++)
{
a[i] = (int *) malloc(10 * a_c);
}
b = (int **) malloc(10 * b_r);
for (int i = 0; i < b_c; i++)
{
b[i] = (int *) malloc(10 * b_c);
}
for (int i = 0; i < a_r; i++)
{
for (int j = 0; j < a_c; j++)
{
a[i][j] = i + j;
}
}
for (int i = 0; i < b_r; i++)
{
for (int j = 0; j < b_c; j++)
{
b[i][j] = i + j;
}
}
int k = 1, d = 1;
for (int i = 0; i < a_r; i++)
{
for (int j = 0; j < a_c; j++)
{
for (int n = -1; n <= 1; n++)
{
for (int e = -1; e <= 1; e++)
{
z = i + n;
r = j + e;
f = k + n;
h = d + e;
if (z < 0 || z > a_r || r < 0 || r > a_c)
{
s = s + 0;
} else {
s = s + a[z][r] * b[f][h]; // runtime error occurs here
}
}
}
a[i][j] = s;
s = 0;
}
}
return 0;
}
這是一個可怕的問題。你有什麼嘗試?這個問題很可能是由於從用戶輸入 – SomeWittyUsername 2013-03-04 15:40:24
接收到的具有越界值的數組所致。該程序的目標是什麼?你爲什麼選擇這些變量名稱?你注意到z,r,f,h,a_r,a_c,b_r,b_c在開始時沒有被初始化嗎?例如,只有s被初始化爲0. – Fitz 2013-03-04 15:41:18
我嘗試瞭解代碼中的縮進,但無法完成 - 例如,某些for-statement似乎缺少了打開大括號。你可以去分析代碼中的縮進和大括號嗎?這將幫助人們更容易地發現問題。 – bouteillebleu 2013-03-04 15:42:02