-1

I know the question is very basic but even after a long search on the web I can't find a solution to my problem. I'd like to familiarize with dynamic arrays in C and, in particular, allocation with malloc() and initialization with memset(), so here's my code:

#include <stdlib.h>

int main()
{   
  double *d;
  int numElements = 3;
  size_t size = numElements * sizeof(double);
  d = malloc(size);
  memset(d,1.0,size);

  int i;
  for(i=0; i < numElements; i++)
    printf("%f\n",d[i]);

  return 0;
}

but the output I get is different from what I expect

0.0
0.0
0.0

Please, can someone be so gentle to explain me what I'm doing wrong?

Thanks!

Federico Nardi
  • 510
  • 7
  • 19
  • 2
    Note: They say [you shouldn't cast the result of `malloc()` in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – MikeCAT Mar 10 '16 at 15:41
  • @MikeCAT if I don't cast the result of malloc() I get the same result – Federico Nardi Mar 10 '16 at 15:54
  • 1
    Which should indicate to you that the cast is completely pointless, which is why you shouldn't use it - it just adds clutter. – Lundin Mar 10 '16 at 15:55
  • [`0x0101010101010101` is the byte representation of `7.74860418548934791663872901834E-304`](http://www.binaryconvert.com/result_double.html?hexadecimal=0101010101010101) – phuclv Mar 10 '16 at 16:00

1 Answers1

0

because memset works with bytes

sizeof(double)==8, so each double in your array is filled with the value 0x0101010101010101

just replace the memset with:

for (int i=0;i< numElements;i++) d[i]=1;
ddy
  • 59
  • 2