Search code examples
carraysmallocmemset

C allocating dynamic array of doubles and initializing it with memset


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!


Solution

  • 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;