Initializing a float array with memset

徘徊边缘 提交于 2019-12-05 01:21:41

Casting a double to an int just creates the binary number 00001010 (10 in binary), and that is the value that is memset'ed. Since it's a char, each of your floats is actually receiving the bit pattern 00001010 00001010 00001010 00001010.

Memset takes a int, but casts it to an unsigned char, and then fills each byte of float (sizeof(float) is probably 4) with that bit pattern. If this is c++, prefer fill instead:

#include <algorithm>
using namespace std;

//...

fill (arry,arry+3,10.0);

No. memset takes a single byte and writes it to the array. A float is a multi-byte type.

EDIT: Yes, I know memset takes an int. But it only uses an unsigned char (a single byte) to fill with.

Why not just a simple for loop?

Actually your try is a little bit misleading, memset works on bytes.. actually using a float for memset value doesn't make any sense!

The float format just has 23+1 bits for mantissa and 8 bits for exponent.. when you write raw bytes values (using memset) inside a float you don't know what you are obtaining because you are setting values that will be interpreted in a different way!

In your snippet you also cast it to (int) turning a 4-bytes float containing 10.0f in a 4-bytes integer containing the value 10.. but as said before if you memset a float with 10 (= 0x0a) you'll end up obtaining 0x0A0A0A0A that is not 10.0f in float format, it can be whatever value (also something very near to 0, like in your case).

Actually memset is useful when you want to initialize an array of chars (since you obtain effectively that value for every char because they are 1 byte long) or when you want to set everything to 0 (NULL) that works for every basic kind of data..

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!