Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is memset(ary,0,length) a portable way of inputting zero in double array [duplicate]

Possible Duplicate:
What is faster/prefered memset or for loop to zero out an array of doubles

The following code uses memset to set all the bits to zero

int length = 5;
double *array = (double *) malloc(sizeof(double)*length);
memset(array,0,sizeof(double)*length);
for(int i=0;i<length;i++)
  if(array[i]!=0.0)
    fprintf(stderr,"not zero in: %d",i);

Can I assume that this will work on all platforms?

Does the double datatype always correspond to the ieee-754 standard?

thanks for your replies, and thanks for the ::fill template command. But my question was more in the sense of the double datatype.

Maybe I should have written my question for pure c. But thanks anyway.

EDIT: changed code and tag to c

like image 938
monkeyking Avatar asked Jun 01 '10 08:06

monkeyking


3 Answers

If you are in a C99 environment, you get no guarantee whatsoever. The representation of floating point numbers is defined in § 5.2.4.2.2, but that is only the logical, mathematical representation. That section does not even mention how floating point numbers are stored in terms of bytes. Instead, it says in a footnote:

The floating-point model is intended to clarify the description of each floating-point characteristic and does not require the floating-point arithmetic of the implementation to be identical.

Further, § 6.2.6.1 says:

The representations of all types are unspecified except as stated in this subclause.

And in the rest of that subclause, floating point types are not mentioned.

In summary, there is no guarantee that a 0.0 is represented as all-bits-zero.

like image 139
Roland Illig Avatar answered Nov 14 '22 09:11

Roland Illig


Use ::std::fill(array, array+length, 0.0);

like image 3
Viktor Sehr Avatar answered Nov 14 '22 10:11

Viktor Sehr


It's not portable. Just use loop. You don't need to cast malloc return value.

like image 3
Nyan Avatar answered Nov 14 '22 09:11

Nyan