I have written a code which calculates the transpose of a matrix NxM using double pointers.
As long as the matrix is square(NxN) it works without problems, but if it isn't, I get this error:
Exception thrown at 0x00052580 in ConsoleApplication27.exe: 0xC0000005: Access violation writing location 0xFDFDFDFD. If there is a handler for this exception, the program may be safely continued.
Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int **alloc(int r, int c) {
int **d;
d = (int **)malloc(r * sizeof(int *));
for (int i = 0; i < r; i++) {
d[i] = (int *)malloc(c * sizeof(int));
}
return d;
}
void input(int **A, int r, int c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("[%d][%d]=", i, j);
scanf("%d", &A[i][j]);
}
}
}
void output(int **A, int r, int c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("%d ", A[i][j]);
}
printf("\n");
}
}
void transpose(int **A, int r, int c) {
int **T = alloc(r, c);
int i, j;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
T[j][i] = A[i][j];
output(T, c, r);
}
void main()
{
int r,c;
scanf("%d%d",&r,&c);
int **A=alloc(r,c);
input(A, r, c);
printf("The transpose of the matrix is: \n");
transpose(A, r, c);
}
Could you point and fix my error for me? I've run this in Visual Studio 2015 and I get that error, and on https://www.onlinegdb.com I get Segmentation fault (core dumped)