jomes
jomes

Reputation: 59

2D struct array: swap row and col?

I want to swap the entire column and row of a 2D struct array.

With this code I can swap rows:

#define N 9 
typedef struct { 
    char number;
    bool editable; 
} FIELD;

int main(){
FIELD **f = (FIELD **) malloc(N * sizeof(FIELD *));
for (i=0; i<N; i++) {
    f[i] = (FIELD *) malloc(N * sizeof(FIELD)); 
}

//example: swap row 0 and row 8
FIELD *tmp;
tmp = f[0];
f[0] = f[8];
f[8] = tmp;
}

But how can I swap an entire column?

Upvotes: 1

Views: 131

Answers (3)

Matias Moreyra
Matias Moreyra

Reputation: 181

To swap an entire column you should iterate over all rows:

//example: swap column 0 and column 8
FIELD tmp;
for (i=0; i<N; i++) {
    tmp = f[i][0];
    f[i][0] = f[i][8]
    f[i][8] = tmp;
}

Upvotes: 1

Roland W
Roland W

Reputation: 1461

You have to swap the columns elementwise. The layout of your array lets you exchange rows by swapping the pointers, but the column elements are each on a separate row.

void swap_cols (FIELD **f, int cola, int colb) {
    for (int i=0; i < N; ++i) {
        FIELD tmp = f[i][cola];
        f[i][cola] = f[i][colb];
        f[i][colb] = tmp;
    }
}

Upvotes: 0

foreverska
foreverska

Reputation: 585

There isn't a pointer swap for columns. You will have to do it algorithmically.

Upvotes: 2

Related Questions