0

I am trying to solve the following problem -

Given a matrix of size M * N. Find the transpose of the matrix.

I intend to store the M*N matrix in an array of pointers and then use a function to return another array of pointers that contains the transpose of the original matrix. Here is the code I used (the code is in C language) -

#include<stdio.h>
#include<stdlib.h>
int **transpose(int **a, int m, int n);
int main()
{
    int **array, m, n;
    scanf("%d%d", &m, &n);
    array=(int **)malloc(m*sizeof(int)); //allocating rows
    for(int i=0; i<m; i++){
        *(array+i)=(int *)malloc(n*sizeof(int));  //allocating columns
    }
    int i, j;
    for(i=0; i<m; i++){
        for(j=0; j<n; j++){
            scanf("%d", *(array+i)+j); //reading input
        }
    }
    int **tranp=transpose(array, m, n);
    for(i=0; i<n; i++){
        for(j=0; j<m; j++){
            printf("%d ", *(*(tranp+i)+j));  //printing output
        }
        printf("\n");
    }
    return 0;
}

int **transpose(int **a, int m, int n)
{
    int **b;
    b=(int **)malloc(n*sizeof(int)); //allocating n rows for transpose
    int i, j;
    for(i=0; i<n; i++){
        *(b+i)=(int *)malloc(m*sizeof(int));  //m columns for transpose
    }
    for(i=0; i<n; i++){
        for(j=0; j<m; j++){
            *(*(b+i)+j)=*(*(a+j)+i);  //b[i][j] is assigned a[j][i]
        }
    }
    return b;  //the pointer to b[0][0] is returned
}

I first declared an array of pointers int **array and used the standard library malloc function to dynamically allocate M rows and N columns. Then I read the input and used the function transpose that has a return type int ** to generate the transpose of the array and assign it to the pointer tranp and print the transposed array.

However, this code works perfectly fine and prints the transposed array for M<5 and N<5. Whenever M>=5 or N>=5, I get the following message -

Process returned -1073741819 (0xC0000005)

I looked up about it and apparently (0xC0000005) is the error code returned because I am illegally accessing memory locations. I do not understand where have I gone wrong here. Why is it that this code works for all M and N less than 5 and fails otherwise?

0 Answers0