указатели на многомерные массивы в классе

0

Я попытался написать программу, но во время работы у меня возникает ошибка сегментации (ядро сбрасывается). Когда я помещаю определенный массив как 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;
}
Теги:
class
arrays
multidimensional-array

1 ответ

1
Лучший ответ

Внутри функции 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];
    }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню