Is memset (ary, 0, length) - portable way to input zero into a double array

Possible duplicate:
What is a faster / preferred memset or for a loop to nullify an array of paired numbers

The following code uses memset to set all 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 it be assumed that this will work on all platforms?

Is the dual data type compliant with the ieee-754 standard?

thanks for your answers, and thanks for the :: fill template command. But my question was more in the sense of a double data type.

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

EDIT: code and tag changed to c

+4
source share
4 answers

If you are in a C99 environment, you do not receive any warranty. The representation of floating point numbers is defined in 5.2.4.2.2, but this is only a logical mathematical representation. This section does not even mention how floating point numbers are stored in bytes. Instead, the footnote says:

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

Further, in § 6.2.6.1 it is said:

Representations of all types are not indicated, except as indicated in this subclause.

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

Thus, there is no guarantee that 0.0 is represented as all bit-zero.

+3
source

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

+4
source

This is not tolerated. Just use a loop. You do not need to specify the return value of malloc.

+3
source

Looks portable to me. since you are using sizeof (double) * length, even if on some strange platform double is 9 bytes, it doesn’t matter at all.

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

-1
source

Source: https://habr.com/ru/post/1311491/


All Articles