Initializing a float array with memset

≯℡__Kan透↙ 提交于 2019-12-12 09:35:06

问题


This is the code that I want to try to write:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

int main(int argc, char *argv[])
{
    float arry[3] = {0};

    memset(arry, (int) 10.0, 3*sizeof(float));

    return 0;
}

My problem is that I want to see if it's possible to use memset to make every entry of an array to be a number other than 0. However, After stepping through that line, the array contents change to a very small number (0). I wonder what I'm doing wrong in this case with using the memset() function. I hope this isn't a duplicate post, as none of the suggested related questions as I'm typing this appears to be.


回答1:


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.




回答2:


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



回答3:


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.




回答4:


Why not just a simple for loop?




回答5:


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..



来源:https://stackoverflow.com/questions/1040070/initializing-a-float-array-with-memset

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