Search code examples
cmemset

C, memset a double array failed


I want to declare a double type array dynamically, so here is my code

void function(int length, ...)
{
    ...

    double *a = malloc(sizeof(double) * length);
    memset(a, 1, sizeof(double) * length);
    for (int i = 0; i < length; i++)
    {
        printf("%f", a[i]);
    }

    ...
}

When I pass a length of 2, the code does not print all 1s. It just prints the following:

7.7486e-304
7.7486e-304

So, what should I do to fix it?


Solution

  • You are confusing setting an array and setting the underlying memory that stores an array.

    A double is made up of 8 bytes. You are setting each byte that makes up the double to 1.

    If you want to initialise each element of the array to 1.0 then you can use a for(;;) loop or since you do seem to be using C++ you can use a container and use a constructor to initialise each element (if the constructor has the ability) or use an algorithm to achieve the same effect.