0

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

Input and output screenshot

theduck
  • 2,589
  • 13
  • 17
  • 23
Michael
  • 82
  • 5

1 Answers1

0

There are several issues:

  • If this is C code, casting the result of malloc is at best pointless and at worst dangerous, as it might hide bugs. (This does not apply for C++ code.)
  • Your "inner" malloc uses sizeof(int*), when it should be using sizeof(int).
  • Your alloc function returns void**, which is not wrong as such, but why not let it return int** instead?
  • This is the most important one: C array indexing starts at zero, so if you have an array of N elements, they are numbered 0 though N-1.
Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15