So I have this program I made which makes a matrix rotate by 90 degrees to the left. The problem is after I run it, it does show me rotated matrix but it crashes giving me this : Gyazo - 1645b2f0f3328381d8cd773c6c96e843.png
Gyazo - f7f3a9280469291ef1331ed119d83821.png
Gyazo - 30de4561f483bb50dfc8fd40c2d1ba04.png
Code :
Code:
#include <stdlib.h>
#include <stdio.h>
int *read_matrix(int *dim)
{
int i,j;
int *A;
printf("Enter the matrix dimension ");
scanf("%d",dim);
A=(int *)malloc((*dim)*sizeof(int));
if (!A)
{
printf("Memory couldn't be allocated'");
exit(1);
}
printf("Memory allocated succesfully \n");
for(i=0;i<*dim;i++)
for(j=0;j<*dim;j++)
{
printf("A[%d][%d] = ",i+1,j+1);
scanf("%d",A+*dim*i+j);
}
return A;
}
int *rotate_matrix(int *A,int dim)
{
int i,j;
int temp;
for ( i=0; i< dim/2 ;i++ )
{
for ( j=i;j<dim-i-1;j++ )
{
temp = *(A+dim*i+j);
*(A+dim*i+j) = *(A+dim*j+dim-1-i);
*(A+dim*j+dim-1-i) = *(A+dim*(dim-1-i)+dim-1-j);
*(A+dim*(dim-1-i)+dim-1-j) = *(A+dim*(dim-1-j)+i);
*(A+dim*(dim-1-j)+i) = temp;
}
}
return A;
}
void show_matrix(int *A,int dim)
{
int i,j;
for(i=0;i<dim;i++)
{
for(j=0;j<dim;j++)
{
printf("%d \t",*(A+dim*i+j));
}
printf("\n");
}
}
void free_m(int *A)
{
if (A!=NULL)
free(A);
}
int main()
{
int i,j;
int *A;
int dim=0;
A=read_matrix(&dim);
printf("Matrix is : \n");
show_matrix(A,dim);
A=rotate_matrix(A,dim);
printf(" The rotated matrix is : \n");
show_matrix(A,dim);
free_m(A);
system("PAUSE");
return 0;
}