简体   繁体   English

C中的memset()不初始化为const double;

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

Hi I have the following code written in C for x86, 嗨,我有以下用C语言为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.. memset的结果只为每个元素返回0.0000,而不是存储在C中的值。

can anyone please help? 谁能帮忙吗?

memset initializes a block of memory with a given byte value. memset用给定的字节值初始化一个内存块。 Bytes are unsigned char , a much smaller unit than double which uses 8 bytes on your architecture. 字节是unsigned char ,比在体系结构中使用8个字节的double单位小得多。 Unless all the bytes of the double value C are identical, memset cannot be used to initialize an array of double values. 除非double memsetC所有字节都相同,否则无法使用memset初始化double值数组。 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. 在符合IEEE-754的系统(例如各种x86变体)上,+ +0.0所有字节的位均为0 ,因此您可以使用memset(array[i], 0, 10 * sizeof(double))将数组初始化为0.0 ,但这既不可读也不便携。 For most other values, It not possible at all. 对于大多数其他值,根本不可能。

You must use a simple for loop: 您必须使用一个简单的for循环:

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. 该循环将由编译器优化,特别是如果C是编译时间常数。

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

memset accepts an int or a constant byte to fill the memory. memset接受一个int或一个常量字节来填充内存。

The value provide by you is a double . 您提供的值是double So how memset is going to deal with it ? 那么memset将如何处理呢?

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 . 您提供的值将隐式转换为int,然后将转换值再次转换为unsigned char以获取字节值

Also, the size_t argument of memset is the number of bytes. 同样,memset的size_t参数是字节数。 You should use, 10 * sizeof(double) instead of just 10 . 您应该使用10 * sizeof(double)而不是10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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