views:

214

answers:

4

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

+3  A: 

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

Viktor Sehr
Or you could use fill_n().
sharptooth
fill_n() is only useful if your container doesn't provide random access.
Viktor Sehr
A: 

looks portable to me. since you use sizeof(double)*length, even if on some strange platform double is 9 bytes, it wont matter at all.

in other words, it doesn't even matter what the ieee spec about doubles says.

Omry
and what if the representation of 0.0 is not all bits cleared [aka, repeated \0]? This is only true if the floating point implementation follows IEEE 754
Mikeage
+2  A: 

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

Nyan
+1  A: 

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.

Roland Illig