Mister Worknor
Mister Worknor

Reputation: 13

C - Transposing a multidimensional array using pointer arithmetic

I've been trying to swap two values in a 2-dimension (MxM) array using pointer arithmetic but can't seem to grasp the pointer magic involved.

Here's what I've got so far:

typedef int Marray_t[M][M];

void transpose(Marray_t A) {
    int i, j;
    int *startAddress = &A[0][0];
    for (i=0; i<M; i++) {
        for (j=0; j<M; j++) {
            int* y = startAddress + (i*M+j);
            int* u = startAddress + (j*M+i);
            int temp;
            temp = *y;
            *y = *u;
            *u = temp;
        }
    }
}

However, I seem to be swapping pointers or pointer values rather than changing the actual values in the array.

Here is the slower version that I'm trying to optimize:

void transpose(Marray_t A) {
        int i, j;
        for (i=0; i<M; i++) {
            for (j=0; j<M; j++) {
                int temp;
                temp = A[i][j];
                A[i][j] = A[j][i];
                A[j][i] = temp;
            }
        }
    }

Upvotes: 1

Views: 1830

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

You seem to swap the value twice resulting into same values.

You should rewrite the loops as

for (i=0; i<M; i++) {
    for (j=0; j<i; j++) {

Live example here

Upvotes: 1

Related Questions