【问题标题】:access violation writing matrix访问冲突写入矩阵
【发布时间】:2017-03-07 14:29:02
【问题描述】:

我正在编写一个二维矩阵程序。

作业要求:

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);

我的代码(main中删除了一些部分,只是创建和调用分配)

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:访问冲突写入位置 0xCDCCDCDD5。如果有这个异常的处理程序,程序可以安全地继续。

它出现在 cin >> matrix[x*rows + cols]; 行处

【问题讨论】:

标签: c++


【解决方案1】:

首先你错过了索引。 应该 cin &gt;&gt; matrix[x*rows + y]; 代替 cin &gt;&gt; matrix[x*rows + cols];

第二个为什么要创建float * 的矩阵而不是float

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

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 2019-09-29
    • 2021-05-04
    • 2011-12-04
    • 1970-01-01
    • 2015-08-15
    • 2020-09-04
    • 2012-12-05
    相关资源
    最近更新 更多