Ethan Wong
Ethan Wong

Reputation: 81

C : How can I swap two objects in a array?

#include <stdio.h>

void t4_trans(int array[3][3]);

int main(int argc, const char * argv[])
{
    //T4
    int array[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    t4_trans(array);

    for (int i = 0; i < 3; i ++)
    {
        for (int j = 0; j < 3; j ++)
        {
            printf("%5i", array[i][j]);
        }
        printf("\n");
    }

    return 0;
}

//T4
void t4_trans(int array[3][3])
{
    for (int i = 0; i < 3; i ++)
    {
        for (int j = 0; j < 3; j ++)
        {
            int t = array[i][j];
            array[i][j] = array[j][i];
            array[j][i] = t;
        }
    }
}

I wrote this code and I thought the result should be:

1 4 7

2 5 8

3 6 9

However, I got the output like this:

1 2 3

4 5 6

7 8 9

I thought it was because the function t4_trans(...) made a new array, so I tried to added

printf("%x", &array);

to both main() and t4_trans(...), but I got the same memory address of the array.

I don't know why the code doesn't work, please help me if you know.

BTW: I'm using xCode 5.1.1 on my MBA, 10.9.4

Thanks.

Upvotes: 0

Views: 111

Answers (1)

Drew McGowen
Drew McGowen

Reputation: 11706

The problem is your code works, but "too well" - you're actually transposing the matrix twice, giving you the original matrix. This is because you loop over all elements, so for example, when you swap array[0][1] and array[1][0], a later iteration will swap array[1][0] and array[0][1], undoing the first swap.

Instead, you only need to start the swap on just half the matrix:

for (int i = 0; i < 3; i ++)
{
    //           vvvvv
    for (int j = i + 1; j < 3; j ++)
    {
        ...

Basically, this swaps only the upper "triangle" with the lower one. It also skips the main diagonal, since it's not affected by transposition.

Upvotes: 2

Related Questions