Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a float array with memset

Tags:

c

memset

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.

like image 448
stanigator Avatar asked Jun 24 '09 18:06

stanigator


2 Answers

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);
like image 142
Todd Gardner Avatar answered Sep 18 '22 02:09

Todd Gardner


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.

like image 28
Jim Buck Avatar answered Sep 20 '22 02:09

Jim Buck