tags:

views:

357

answers:

4

Is is possible to memcpy from a double array to a float array safely?

+17  A: 

Depends on what you want. The values certainly won't be preserved. If you need that, use std::copy.

#include <algorithm>

int main()
{
    double a[] = {1.618, 3.1416, 2.7, 0.707, 1.0};
    float b[5];
    std::copy(a, a + 5, b);
}
FredOverflow
+11  A: 

No.

Daniel Daranas
Comments must be at least 15 characters long, but this does not hold for answers? Strange :)
FredOverflow
Answers must be at least 15 characters long, too :)
Daniel Daranas
@Daniel Daranas: Haha ! Just saw your ugly hack to "overcome" the limitation. Clever ;)
ereOn
@ereOn: I used to just add "May the force be with you." to my short answers, but then... http://meta.stackoverflow.com/questions/47689/how-to-attach-a-file-on-stackoverflow/47691#47691
Daniel Daranas
Uninspired. The commonly accepted way to do it is to repeat "Screw Flanders" until you get the required number of characters.
AndreyT
*​​​​​​​​​​​​​*
Michael Myers
+2  A: 

The problem is that there is no guarantee that the compiler's binary representation of a double is the equivalent representation of a float. In order to use memcpy for multi-byte types is that the underlying representation must be the same (same layout). You can safely copy float to float, int to int and double to double.

You are destined for undefined behavior when the source type does not match the destination type, such as copying from long to char or float to double. The memcpy function does not make any conversion or perform any promotions. It just copies.

Thomas Matthews
+1  A: 

In general case - no.

In specific cases, on a given platform the representation of float and double might be the same, and the copy will succeed. But it doesn't make any practical sense anyway.

AndreyT