i do this in the education purpose.
such is idea:
i have class Array. I inheritance it in class Darray, and add necessary dimension
it likes so:
main.cpp
int main(int argc, char *argv[])
{
Array obj;
obj.output();
DArray obj2;
obj2.output();
return 0;
}
header
class Array
{
public:
int *x,sizem; //одно измерение, массив
// можно объявить здесь как **x , но это не то
Array();
~Array();
virtual void output();
};
class DArray:public Array
{
public:
int **z;
int sizen;
DArray();
~DArray();
virtual void output();
};
realisation.cpp
Array::Array()
{
sizem=5;
x=new int[sizem];
for(int i=0;i<sizem;i++)
x[i]=i;
}
Array::~Array()
{
delete []x;
}
void Array::output()
{
for(int i=0;i<sizem;cout<<x[i]<<" ",i++);
cout<<"\n";
}
void DArray::output()
{ cout<<"\n";
for(int i=0;i<sizem;i++)
{ for(int j=0;j<sizen;j++)
cout<<z[i][j]<<" ";
cout<<"\n";
}
}
DArray::DArray()
{
int i;
sizen=sizem;
z=new int*[sizem]; // одно измерение уже есть, т.е. это одна строка
for(i=1;i<sizem;i++)
z[i]=new int[sizem];
for(int i=1;i<sizem;i++) // if i don't initialization matrix, all'll
works right,compiles,and run, but AFAIK when i allocate space dynamically,
it must be intitializationed self by zeros, but it isn't particually equal
zeroes, the fisrt two column are equal some random number, other
are equal zero.
for(int j=0;j<sizen;j++)
{
z[i][j]=2;
}
*z=x; // i've already array x , that was inheritanced, just point address
}
DArray::~DArray()
{
for(int i=1;i<sizem;i++)
delete z[i];
// yet one problem
// i can't delete x e.g. delete []x
// but it should work!
delete []z;
}
PS I works without errors, but i think there are memory leak, but can’t catch up why
all tricks has been done in constructor, everything other is general stuff like output matrix/array. that’s why i think that problem is there
thanks you mates!
but i don’t understand yet one thing
z=new int*[sizem];
for(i=1;i<sizem;i++)
z[i]=new int[sizem];
for(int i=1;i<sizem;i++)
{
for(int j=0;j<sizen;j++)
cout<<z[i][j]<< " ";
cout<<"\n";
}
as i think i have to receive here ones zeros. byt i receive something like
2532336 2532336 0 0 0
2532336 2532336 0 0 0
2532336 2532336 0 0 0
2532336 2532336 0 0 0
Why?
There are no memory leaks, but there is one mismatch between new and delete:
You’re using
new[]here:but you’re using
delete(notdelete[]) here:With that changed to
delete[] z[i];, there are no warnings from valgrind:EDIT: regarding your second question, if you want the arrays to be initialized with zeroes, use
or just use vectors like everybody else.