c++ - 指向类中多维数组的指针

标签 c++ arrays class multidimensional-array

我尝试编写一个程序,但在运行时出现段错误(核心已转储)。当我放置一个像 array_2d[10][1] 这样的定义数组时,问题就解决了,但我需要为我的项目分配内存。这是我的代码的一个简单版本:

#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

class Exam
{
    private:
        double** array_2d;
        unsigned int num;
        unsigned int num1;
    public:
        Exam();
        void memoryallocation();
        void show();
};

Exam::Exam()
{
    num=10;
    num1=1;
}

void Exam::memoryallocation ()
{
    double** array_2d = new double*[num];
    for (unsigned int i = 0; i < num ;i++) 
    {
        array_2d[i] = new double[num1];
    }
}

void Exam::show ()
{
    ifstream file;
    file.open("fish.txt");
    for (unsigned int i = 0; i < num; i++) 
    {
        for (unsigned int j = 0; j < num1; j++) 
        {
            file >> array_2d[i][j];
            cout<<array_2d[i][j]<<" ";
        }
        cout<<endl;
    }

    file.close();
}

int main()
{
    Exam E;
    E.memoryallocation();
    E.show();
    return 0;
}

最佳答案

在函数 Exam::memoryallocation () 中,您再次声明了 array_2d。

void Exam::memoryallocation ()
{
    array_2d = new double*[num]; //remove the redeclaration of array_2d
    for (unsigned int i = 0; i < num ;i++) 
    {
        array_2d[i] = new double[num1];
    }
}

关于c++ - 指向类中多维数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19332440/

相关文章:

c++ - 在 Makefile 中使用 exit 命令导致编译错误

c++ - 重载的 const 和非 const 类方法在 C++ 中返回引用

c++ - 可变参数模板类未完全展开

c++ - 判断点是否在矩形内

c++ - 排序算法的枢轴选择不正确

arrays - 根据同一文档中的另一个数组查询 Mongo 文档数组

arrays - C 中函数参数中的固定数组或指针之间的区别?

c++ - 读取文件并删除重复的字母

class - 深层类继承层次结构——坏主意?

c# - XAML 为转换器类添加命名空间