null
null

Reputation: 133

Finding transpose of matrix using pointer (what is wrong with my code?)

Can you just tell me what is wrong with my logic in the below code? I am trying to do transpose of a matrix but the output is coming wildly wrong. For example I initiate a matrix in my main function :

int a[2][2]; 
a[0][0]=1;
a[0][1]=2; 
a[1][0]=3; 
a[1][1]=4; 
int *a1;

a1=&a[0][0];

and then do

transpose(a1,2,2); 

The output gives : [16 , 16], [3 , 16]. But output should've been [1 , 3] , [2 , 4].

int* transpose(int *a,int m,int n)
{
    int i,j;
    int tmp;
    for(i=0;i<m;i++)
    {
            for(j=0;j<n;j++)
            {
                    *(a + i*m + j) = tmp;
                    *(a + i*m + j) = *(a + i + j*m);
                    *(a + i + j*m) = tmp;
            }
    }
    return a;
}

Upvotes: 0

Views: 72

Answers (1)

Henning Koehler
Henning Koehler

Reputation: 2637

Your first assignments in the swap is the wrong way around, so you are coping values from the unassigned tmp variable. Your swap code should read

tmp = *(a + i*m + j);
*(a + i*m + j) = *(a + i + j*m);
*(a + i + j*m) = tmp;

Upvotes: 2

Related Questions