2017-03-07 8 views
1

私は2dマトリックスプログラムを書いています。割り当てのためのアクセス違反書き込みマトリックス

要件:

Implement the following functions: 
float *allocate(int rows, int cols); 
void readm(float *matrix, int rows, int cols); 
void writem(float *matrix, int rows, int cols); 
void mulmatrix(float *matrix1, int rows1, int cols1, float *matrix2, int cols2, float *product); 

私のコード(一部だけの作成と割り当て呼び出し、メインで削除)

int main() { 
float * matrix1; 
float * matrix2; 
matrix1 = allocate(rows1,cols1); 
matrix2 = allocate(rows2,cols2); 
} 

float *allocate(int rows, int cols) { 
    float ** matrix = new float *[rows * cols]; 
    return *matrix; 
}//end allocate 

void writem(float *matrix, int rows, int cols) { 
    for (int x = 0; x < rows; x++) { 
     for (int y = 0; y < cols; y++) { 
      cout << "enter contents of element at " << (x + 1) << ", " << (y + 1) << " "; 
      cin >> matrix[x*rows + cols]; 
     } 
    } 
}//end writem 

私はスローエラー

例外を取得lab5.exeの0x0FECF6B6(msvcp140d.dll)で:0xC0000005:場所0xCDCDCDD5を書き込むアクセス違反。この例外のハンドラがある場合は、プログラムを安全に継続することができます。

これは、行cin >> matrix [x * rows + cols]で発生します。

+2

このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –

+2

このエラーは、初期化されていないポインタを間接参照していることを示します。 –

+0

これは、初期化されていないヒープポインタです:http://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations/127404#127404 – drescherjm

答えて

2

まず、あなたはインデックスを欠場しました。 cin >> matrix[x*rows + y]; 代わりの cin >> matrix[x*rows + cols];

第二に、なぜあなたはfloat *だけではなくfloatのマトリックスを作成したいんべきか?

float *allocate(int rows, int cols) { 
    float* matrix = new float[rows * cols]; 
    return matrix; 
}//end allocate 
関連する問題