0

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; } 
1
  • Please flag the language you are using. Commented Oct 12, 2013 at 9:39

1 Answer 1

1

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]; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.