【问题标题】:Runtime pointer-exception while copying one array to another inside a function在函数内将一个数组复制到另一个数组时出现运行时指针异常
【发布时间】:2019-10-14 07:41:48
【问题描述】:

主要目标是从main() 函数的构造函数中复制一个数组。使用cin >> 真的很容易,但是我必须给构造函数一个已经定义好的数组。编译程序时我没有收到任何错误。只有在运行时它才会失败并出现以下异常:

抛出未处理的异常:读取访问冲突。 this->A 是 0x1110112.

我已经尝试在类中定义这些数组,尽管我知道这不是一个好习惯。但我不能这样做,因为它会导致此类中定义的另一个函数中的指针出错。这是我到目前为止得到的:

#include "pch.h"
#include <iostream>
#include <iomanip>
#define size 5
using namespace std;
class Matr
{
private:
    //const int size = 5;
    double **A;
    double *B;
public:
    Matr(double (*a)[size], double b[]) {
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                A[i][j] = a[i][j]; //here exception falls
            }
            B[i] = b[i];
        }
    }
};
int main()
{ 
    double A[5][5] = {              {-6,18,15,8,6},
                    {2,11,-18,17,23},
                    {-13,-2,8,-10,-5},
                    {1,13,11,-10,-5},
                    {10,21,8,-1,11} };
    double B[5] = { 0,-8,1,-2,-6 };
    Matr matr(A,B); //define the arrays
}

我想将此定义为类中的数组,以便在其他函数中使用它们。这甚至可能吗? :D

【问题讨论】:

  • A 在分配给它时未初始化。它只是一个普通的指针,没有分配任何内存。

标签: c++ arrays pointers


【解决方案1】:

Matr 构造函数中,您应该使用newAB 分配内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2022-07-05
    • 1970-01-01
    • 2018-04-16
    相关资源
    最近更新 更多