For some reason the element b[m][n]
is a random number instead of being 1. The same thing happens if I try to printf a[n][m]
. Please I need some help on this!
#include <stdio.h>
#include <stdlib.h>
void **alloc(int n,int m)
{
int **x=(int**)malloc(n*sizeof(int*));
for(int i=1; i<=n; i++)
x[i] =(int*)malloc(m*sizeof(int*));
return x ;
}
void read(int **a,int n,int m,FILE *f)
{
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
fscanf(f,"%d",&a[i][j]);
}
void print(int **a,int n,int m)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
void transpose(int **a,int n,int m,int ***b)
{
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
b[j][i]=a[i][j];
}
int main()
{
int n,m;
FILE *f;
f=fopen("in.txt","r");
if(f==NULL)
printf("Error");
fscanf(f,"%d %d",&n,&m);
int **a=alloc(n,m);
read(a,n,m,f);
int **b=alloc(m,n);
transpose(a,n,m,b);
print(b,m,n);
return 0;
}
This is the input and output, everything works except the b[m][n] element