what is wrong with this example of dynamic 2D array? It gives segmentation fault on execution.

#include <iostream>

using namespace std;

class TwoDArray
{
private:
int** Array;
int row;
int col;
public:
TwoDArray(int m=2, int n=3);
~TwoDArray();
void display() const;
void initialize();
};

TwoDArray::TwoDArray(int n, int m)
{
row = n;
col = m;
int** Array = new int*[row];
for(int i=0; i<row; i++)
Array[i] = new int[col];
return;
}

TwoDArray::~TwoDArray()
{
for(int i=0; i<row; i++)
delete [] Array[i];
delete [] Array;
}

void TwoDArray::display() const
{
for(int i=0; i<row; i++)
for(int j=0; j<col; j++)
cout << "Array [" << i << "][" << j << "] : " << Array[i][j] << "\t" ;
cout << endl;
}

void TwoDArray::initialize()
{
for(int i=0; i<row; i++)
for(int j=0; j<col; j++)
{
cout << "enter A["<<i<<"]["<<j<<"] : ";
cin >> Array[i][j];
}
return;
}

int main(int argc, char* argv[])
{
TwoDArray arr = TwoDArray(3,4);
arr.display();
arr.initialize();
arr.display();
return 0;
}
The first thing that jumps out at me is that the defaulted copy constructor and assignment operator aren't going to work for you.

[Edit: The second thing that jumps out at me is that local variables of member functions with the same name as member variables shadow the member variables. For instance the local variable Array in your constructor is not related to the member variable Array which remains uninitialized after the constructor execution.]
Last edited on
Try to change

TwoDArray arr = TwoDArray(3,4);

to

TwoDArray arr(3,4);
@cire I got your point actually it was a very silly mistake I need to remove int before int** Array from the constructor.

Thanks a lot.
Topic archived. No new replies allowed.