A tried to copy one array, e.g.
for(int i = 0;i < n; ++i)
for(int j = 0; j < n; ++j)
B[i][j] = A[i][j];
But when I change elements of A, also elements of B are changed. How to avoid this?
A tried to copy one array, e.g.
for(int i = 0;i < n; ++i)
for(int j = 0; j < n; ++j)
B[i][j] = A[i][j];
But when I change elements of A, also elements of B are changed. How to avoid this?
Your question is not clear. But I think you have two arrays such that dereferencing and updating one also updates the other. This implies that the two are merely pointers to the same underlying array. Rather what you need is two seperate arrays that have their own memory.
So, allocate memory for A
and B
seperately
// Correct Version :
int *A = new int[K];
int *B = new int[K];
And
//Incorrect Version:
int *A = new int[K];
int *B = A;
Ideally, you would use std::vector< vector<int> >
or a library component like boost::ublas::matrix<int>
Something like this, if you know the size of the arrays at compile-time:
const int n = 30;
int A[n][n];
int B[n][n];
//Populate A here...
//Now copy A to B:
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
B[i][j] = A[i][j];