Is is possible to memcpy from a double array to a float array safely?
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);
}
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.
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.