Reputation: 137
I tried to write a program but I get segmentation fault (core dumped) while running . When I put a defined array like array_2d[10][1] , the problem is solved but I need to do the memory allocation for my project. It is a simple version of my code:
#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;
}
Upvotes: 0
Views: 126
Reputation: 3334
Inside the function Exam::memoryallocation ()
, you are declaring array_2d again.
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];
}
}
Upvotes: 1