I am encountering some memory issues while working with a 2 dimensional array in c++.
Excerpt from main:
int **A,**B,**C;
A = new int*[d];
B = new int*[d];
C = new int*[d];
if (file.is_open()){
for (int i = 0; i < d ;i++){
A[i] = new int[d];
C[i] = new int[d];
for(int j = 0; j < d ;j++){
if(getline(file,line)){
A[i][j] = atoi(line.c_str());
}else{
cout<<"Dimension does not match inputfile.\n";
return(1);
}
}
}
for (int i = 0; i < d ;i++){
B[i] = new int[d];
for(int j = 0; j < d ;j++){
if(getline(file,line)){
B[i][j] = atoi(line.c_str());
}else{
cout<<"Dimension does not match inputfile.\n";
return(1);
}
}
}
file.close();
}
...
cout<<"A4\n";
PrintM(A,n);
AddMatrix(B,bi,bj,B,bi,bj+n/2,C,ci,cj,n/2);
cout<<"A5\n";
PrintM(A,n);
...
The add matrix routine:
void AddMatrix(int** X,int ai,int aj,int** Y, int bi,int bj,int** Z,int ci,int cj,int n){
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
Z[i+ci][j+cj] = X[i+ai][j+aj] + Y[i+bi][j+bj];
}
The PrintM routine:
void PrintM(int **P,int n){
for (int i=0;i<n;i++){
cout<<"[";
for (int j=0;j<n;j++){
if (j != n-1)
cout<<P[i][j]<<",";
else
cout<<P[i][j]<<"]\n";
}
}
cout<<endl;
}
And the output:
A4
[0,0]
[0,0]
A5
[4,0]
[0,0]
I have no idea why the array A is being modified in the AddMatrix routine, as I'm not even using it in the call to the routine. I haven't included all the code here (300 lines long), but I couldn't recreate the problem in a short example. I'm not doing anything silly like saying A = C anywhere. I can't figure out where I'm going wrong.