finding matrix transpose - why doesn't it work when passing pointer argument?
Hi
I'm adapting some code I've written using 2d arrays (to represent matrices) to handle large arrays such that double matrix[][] goes to double **matrix and then I'm using malloc.
It seems to work fine for part of my program up to where I have to find the matrix transpose at which point it does something I don't understand. I've taken that bit of code out and run it by itself (included below), get the same problem... which is that the input matrix is getting modified when the function is called, here's an example for a test 3 by 3:
The input is:in[0][0] = 10.000000
in[0][1] = 10.000000
in[0][2] = 10.000000
in[1][0] = 5.000000
in[1][1] = 5.000000
in[1][2] = 5.000000
in[2][0] = 3.333333
in[2][1] = 3.333333
in[2][2] = 3.333333
but after being passed to find_transpose is comes out as:in[0][0] = 10.000000
in[0][1] = 10.000000
in[0][2] = 10.000000
in[1][0] = 10.000000
in[1][1] = 5.000000
in[1][2] = 10.000000
in[2][0] = 3.333333
in[2][1] = 3.333333
in[2][2] = 10.000000
and the actual transpose output is:
out[0][0] = 10.000000
out[0][1] = 10.000000
out[0][2] = 10.000000
out[1][0] = 10.000000
out[1][1] = 5.000000
out[1][2] = 3.333333
out[2][0] = 10.000000
out[2][1] = 10.000000
out[2][2] = 10.000000
I really don't understand why!
Can anyone help?
Thanks
jbd
nt find_transpose(int n, double **a, double **b)
{
int I,j;
for (I=0; I<n; I++)
{
for (j=0; j<n; j++)
b[i][j] = a[i][j];
}
for (I=0; I<n; I++)
{
for (j=0; j<n; j++)
b[i][j] = a[j][i];
}
}
int main (void)
{
int I, j, p=3;
double **in, **out;
in = malloc(p * sizeof(int *));
out = malloc(p * sizeof(int *));
for (I=0; I<p; I++){
in[i]= malloc(p * sizeof(int *));
out[i]= malloc(p * sizeof(int *));}
for (I=0; I<p; I++)
{
for (j=0; j<p; j++)
{in[i][j]= 10./(I+1);
printf("in[%i][%i] = %f\n", I, j, in[i][j]);
}
}
find_transpose(p, in, out);
for (I=0; I<p; I++)
{
for (j=0; j<p; j++)
printf("in[%i][%i] = %f\n", I, j, in[i][j]);
}
for (I=0; I<p; I++)
{
for (j=0; j<p; j++)
printf("out[%i][%i] = %f\n", I, j, out[i][j]);
}
return 0;
}