2017-03-07 120 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 >>矩阵[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