0

`Dear friends, I was trying to define a 2-D array named A using a dummy variable m through malloc.The variable A has been initialized to 0. It is expected that new values get assigned to the matrix after the run .But that doesn't happen here.I would like to understand the correct way of doing this.I also tried method described in dynamic memory allocation in 2d array and using scanf and also avoided casting malloc. Here is the code

#include<stdio.h>
#include<math.h>
#include<conio.h>
#include<stdlib.h>
double** Allocate(int d1,int d2);
double** Allocate(int d1,int d2)
{  
  double **m;
  int i,j;
  m = (double**)malloc(sizeof(double*)*d1);  
  for(i=0;i<d1;i++)
  {
    m[i]=(double*)malloc(sizeof(double)*d2);
  }
  for(i=0;i<d1;i++)
  {
    for(j=0;j<d2;j++)
    {
        m[i][j]=0.0;
    }
  }
  return m;
 }
 main()
{
int i,j;
int n=3;
float x[n],y[n];
double** A= Allocate(n,n);  
    for(i=0;i<=n-1;i++)
   {
    for(j=0;j<=n-1;j++)
    {
     scanf("%f",&A[i][j]);
    }
  }
  for(i=0;i<=n-1;i++)
   {
    for(j=0;j<=n-1;j++)
    {
     printf("%f\t",A[i][j]);
    }printf("\n");
  }
 }
Community
  • 1
  • 1

1 Answers1

1
  • You are using the wrong format specifier for scanning a double type variable here :

    scanf("%f",&A[i][j]);
            ^ 
    
  • The correct format specifier is %lf, so instead scan this way into the array :

    scanf("%lf",&A[i][j]);
    

  • You need not use %lf while using printf() because as @Robᵩ suggested in the comment :

in printf(), %f is identical to %lf. Both accept a double

to know more, see this : click


  • further, don't use main() as it is not a valid signature for main(), instead use int main(void),because in standard C, the only valid signatures for main are:

    int main(void) //when arguments are not required
    
  • And also,

    int main(int argc, char **argv) //when you require to send arguments

to know more, see this : click


  • And always make sure to free the malloced memory at the end

      ..........  
         printf("%lf\t",A[i][j]);
        }printf("\n");
      }
    
      //freeing the malloced memory
      for(i=0; i<n; i++)
      {
          free(A[i]);
      }
      free(A);
    
    }//end of main
    

Making above changes, your main() function would be :

int main(void)
{
    int i,j;
    int n=3;

    double** A= Allocate(n,n);

    for(i=0;i<=n-1;i++)
    {
        for(j=0;j<=n-1;j++)
        {
            scanf("%lf",&A[i][j]);
        }
    }

    for(i=0;i<=n-1;i++)
    {
        for(j=0;j<=n-1;j++)
        {
             printf("%f\t",A[i][j]);
        }
        printf("\n");
     }

      for(i=0; i<n; i++)
      {
          free(A[i]);
      }
      free(A);
 }
Community
  • 1
  • 1
Cherubim
  • 5,287
  • 3
  • 20
  • 37
  • 2
    You are absolutely correct w.r.t. `scanf()`. But, in `printf()`, `%f` is identical to `%lf`. Both accept a `double`. – Robᵩ Jul 20 '16 at 16:21