简体   繁体   中英

memset() in C not initialising to a const double;

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.

void *memset(void *s, int c, size_t n);

memset accepts an int or a constant byte to fill the memory.

The value provide by you is a double . So how memset is going to deal with it ?

The value provided by you will be implicitly casted to int and then the casted value will again be casted to unsigned char to get a byte value .

Also, the size_t argument of memset is the number of bytes. You should use, 10 * sizeof(double) instead of just 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM