I have a quadratic matrix(two-dimensional dynamic array of pointers) and need to change rows/columns order. The matrix is very big that’s why I have decided just to change pointers instead of copying all of elements. I also have another array which specifies a computation.
Rows permutation specifies this way:
4,3,2,1 – it means that the first row must be on the fourth place, the second row must be on the third place, etc.
The same situation is with the columns.

How to implement such algorithm of changing of rows order(permutation of of pointers)? Here it is my version, but it doesn’t work. I want to copy pointers but element is copied instead of it and then appears a segmentation fault.
When I add ‘&’ to get address, the compiler says that it is a syntax error:
orderOfRows[i] = &auxMatrix[computation[i]];
Here it is my code:
static int N = 6;
static int **orderOfRows;
int **sourceMatrix;
int **auxMatrix;
int main() {
int* computation = (int*)malloc(N*sizeof(int));
computation[0] = 1;
computation[1] = 6;
computation[2] = 3;
computation[3] = 7;
computation[4] = 4;
computation[5] = 2;
}
printf("After computation has been done: \n");
changeRowOrder(computation);
void changeRowOrder(int *computation) {
int i;
// change rows order and dopy them into a temp array
for(i = 0; i < N; ++i) {
// static arrays
orderOfRows[i] = auxMatrix[computation[i]];
}
// recover matrix
for(i = 0; i < N; ++i) {
auxMatrix[i] = orderOfRows[i];
}
void allocate2dMemory() {
int i = 0;
sourceMatrix = (int**)malloc(N * sizeof(int *));
if(sourceMatrix == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
for(i = 0; i < N; i++) {
sourceMatrix[i] = (int*)malloc(N * sizeof(int));
if(sourceMatrix[i] == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
}
auxMatrix = (int**)malloc(N * sizeof(int *));
if(auxMatrix == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
for(i = 0; i < N; i++) {
auxMatrix[i] = (int*)malloc(N * sizeof(int));
if(auxMatrix[i] == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
}
orderOfRows = (int**)malloc(N * sizeof(int *));
if(orderOfRows == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
for(i = 0; i < N; i++) {
orderOfRows[i] = (int*)malloc(N * sizeof(int));
if(orderOfRows[i] == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
}
}
}
I will spend 2*N(copy pointers and then recover) operations instead of N*N.
And I have another question: how I can do the permutation of columns using this idea? If it isn’t possible how can I do the permutation of columns but not to copy all elements of the matrix? The programming language is only C.
Instead of
you should have
And one more thing:
if you have
computation[1] = 6, it means that by doingauxMatrix[computation[i]]you try to accessauxMatrix[6], which you can’t do becauseauxMatrix‘s size is 6×6.