I have got some trouble in learning c++. The code below I can complie, but run crash when i debug (the picture I poste), but I can find the true problem of the code. The compile tools I use is dev++.
The doubt point is memcpy(array,ar.getArray(),r*c*sizeof(array[0][0]));
because some guy tell me it is shallow copy not deep copy, in fact, what I want to do is to copy the value not the address.
Code:
#include<iostream>
#include<cstdlib>
using namespace std;
class Array2 {
private:
int r;
int c;
int **array;
public:
Array2 (){
cout<<"no character constructor"<<endl;
//k=1;
}
Array2 (int row,int colume);
~Array2()
{
if(array)
{
cout<<"deconstructor called!"<<endl;
for(int i=0;i<r;++i)
{
delete [] array[i];
}
delete [] array;
}
}
int * operator [] (int & i);
int & operator () (int & i,int & j);
Array2 & operator = ( Array2 & ar);
void setR(int row){
r=row;
}
void setC(int colume){
c=colume;
}
int getR() {
return r;
}
int getC() {
return c;
}
int** getArray() {
return array;
}
};
Array2 & Array2:: operator = ( Array2 & ar){
cout<<"= character constructor"<<endl;
r=ar.getC();
c=ar.getR();
array=new int*[r*c];
for(int i=0;i<r;i++){
array[i]=new int[c];
}
memcpy(array,ar.getArray(),r*c*sizeof(array[0][0]));
return *this;
}
int & Array2:: operator () (int & i,int & j){
return array[i][j];
}
int * Array2:: operator [] (int & i){
//return a[i];
return array[i];
}
Array2:: Array2(int row,int colume ):r(row),c(colume)
{
cout<<" character constructor"<<endl;
array=new int*[r];
for(int i=0;i<r;i++){
array[i]=new int[c];
}
}
int main()
{
Array2 a(3,4);
int i,j;
for(i=0;i<3;++i)
{
for(j=0;j<4;j++)
{
a[i][j]=i*4+j;
}
}
for(i=0;i<3;++i)
{
for(j=0;j<4;++j)
cout<<a(i,j)<<",";
cout<<endl;
}
cout<<"next"<<endl;
Array2 b;
Array2 c(3,4);
b=a;
for(i=0;i<3;++i)
{
for(j=0;j<4;++j)
cout<<b(i,j)<<",";
cout<<endl;
}
if(&a==&b)
cout<<"a and b adress is the same"<<endl;
else
{
cout<<"a and b adress is not the same"<<endl;
cout<<"a:"<<a.getArray()<<","<<"b:"<<b.getArray()<<endl;
}
if(&a!=&c)
cout<<"a and c adress is not the same"<<endl;
cout<<"a:"<<a.getArray()<<","<<"c:"<<c.getArray()<<endl;
return 0;
}