Home > Net >  Dynamic memory allocation - Malloc
Dynamic memory allocation - Malloc

Time:11-10

I try to allocate the memory of the array dynamically using malloc function. The array (d) is composed of two vectors. The code is as follows:

#include <stdio.h>

void main()
{
   
  int ind;
  int nlfc;
  double x[5], y[5], z[5];
  nlfc=4;
  double **d;
  double dt[3][nlfc];

   d=malloc(4*sizeof(double));
    for(ind=0; ind<nlfc; ind  ) {
    d[ind]=malloc(4*sizeof(double));
  }
  x[4]=0;
  y[4]=0;
  z[4]=0;
  x[0]=-1;
  x[1]=0;
  x[2]=1;
  x[3]=0;
  y[0]=0;
  y[1]=-1;
  y[2]=0;
  y[3]=1;
  z[0]=0;
  z[1]=0;
  z[2]=0;
  z[3]=0;
  for (ind=0;ind<nlfc;ind  ){
      d[ind][0]=x[ind]-x[4];
      d[ind][1]=y[ind]-y[4];
      d[ind][2]=z[ind]-z[4];
      
   }
 
    for (ind=0;ind<nlfc;ind  ){
      printf("%f\n",sizeof(d[ind][1]));     
   }
   
 free(d);

  }

The output is as follows:

0.000000 0.000000 0.000000 0.000000

But the output needs to be as follows:

-1 0 1 0

So it seems I implemented malloc function in a wrong way. Could you help me how to implement correctly malloc function in this code?

Kind regards

CodePudding user response:

This:

d=malloc(4*sizeof(double));

is wrong, d has type double **. It should be:

d = malloc(4 * sizeof *d);

which will allocate space for four pointers to double. A handy rule of thumb is to always de-reference the pointer with sizeof when calling malloc(), never repeat the type since you might get it wrong.

As pointed out in a comment, you must call free() exactly once for each pointer returned by all malloc() calls, a single call is not enough.

CodePudding user response:

You wrote:

printf("%f\n",sizeof(d[ind][1]));  

which means to work out the number of bytes that a double takes up (that's 8) then give the integer 8 to printf but tell printf it's actually a double, which causes printf to read some garbage double from somewhere and print it - apparently 0 in your case (but it could be something else for someone else).

You probably meant:

printf("%f\n",d[ind][1]);

without sizeof.

Also this:

d=malloc(4*sizeof(double));

should be this:

d=malloc(4*sizeof(double*));
//                      ^
//                      |
//                  added a *

although I'm not aware of any computer systems where double uses less bytes than double*, so your program does allocate enough bytes either way.

CodePudding user response:

You can allocate a 2d array using a pointer to an array. Just do:

double (*d)[4] = calloc(4, sizeof *d);

Remember to call free(d) when d is no longer needed.

  • Related