Initializing a float array with memset

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);

Why not just a simple for loop?


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.


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.

Tags:

C

Memset