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;
}
4

1 に答える 1

1

function 内で、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];
    }
}
于 2013-10-12T09:13:42.780 に答える