Hi I have the following code written in C for x86,
const double N = 4;
const double C = 1.0 / N; <---- 0.2500
double *array = (double*)calloc(10, sizeof(double));
memset(array, C, 10);
the result of the memset only returns 0.0000 for each element instead of the value stored in C..
can anyone please help?
memset
initializes a block of memory with a given byte value. Bytes are unsigned char
, a much smaller unit than double
which uses 8 bytes on your architecture. Unless all the bytes of the double
value C
are identical, memset
cannot be used to initialize an array of double
values. On IEEE-754 compliant systems such as the various x86 variants, +0.0
has all bytes with all bits 0
, so you could use memset(array[i], 0, 10 * sizeof(double))
to initialize the array to 0.0
, but this is neither readable nor portable. For most other values, It not possible at all.
You must use a simple for
loop:
for (int i = 0; i < 10; i++)
array[i] = C;
The loop will be optimized by the compiler, especially if C is a compile time constant.