Hi i'm having trouble with a function that simply computes the transpose of a 2D array. It works fine for square arrays, but then seg faults on non-square arrays. Any Suggestions on what might be wrong?
Code:
#include "stdio.h"
#include "stdlib.h"
void transpose(int rows, int cols, double** orig_arr, double** transpose){
//transpose[cols][rows] = orig_arr[rows][cols];
int i, j;
for(i=0;i<rows; i++) {
for (j=0; j<cols; j++){
transpose[j][i]=orig_arr[i][j];
}
}
}
int main(){
int row;
int col;
int i=0; //counter for for loops
int j=0; //counter for for loops
float x;
printf("How man rows would you like to imput? :");
scanf("%i", &row);
printf("How man cols would you like to imput? :");
scanf("%i", &col);
/* Allocate space for the imput array:*/
double** arr=(double**) malloc(row * sizeof(double*));
for(i=0;i<col;i++) {
arr[i]=(double*) malloc(col * sizeof(double));
}
/* Allocate space for the transpose array:*/
double** transpose_arr=(double**) malloc(col* sizeof(double*));
for(i=0;i<row;i++) {
transpose_arr[i]=(double*) malloc(row * sizeof(double));
}
/*Read in the elements of the array*/
for(i=0;i<row;i++) {
printf("\nEnter your value for row %i:\n arr[%i]", i, i);
for(j=0;j<col;j++) {
if (j==0) //If statemet just makes the
{printf("arr[%i]:", j); //printing on the screen look
} //orderly.
else {printf(" arr[%i]:", j);
}
scanf("%f", &x);
arr[i][j]=x;
}
}
/*Print back the array to the user*/
printf("Your array is:\n");
for(i=0;i<row;i++) {
for (j=0; j<col; j++){
printf("%f ", arr[i][j]);
}
printf("\n");
}
printf("\n");
/*Call function to compute the transpose of the imput array*/
printf("The transpose of that array is:\n");
transpose(row, col, arr, transpose_arr);
for(i=0;i<row;i++) {
for (j=0; j<col; j++){
printf("%f ", transpose_arr[i][j]);
}
printf("\n");
}
printf("\n");
free(arr);
free(transpose_arr);
arr=NULL;
transpose_arr=NULL;
return 0;
}
Thanks so much!