I have a pointer float *ptr, after dynamic allocation with length n, I want to initialize this array with zero or one, so I use memset(ptr,0,n*sizeof(float)) or memset(ptr,1,n*sizeof(float)). Is this legal? Because the second argument of memset is int-type, I'm afraid it cannot be applied to float-type.
2 Answers
memset(ptr,1,n*sizeof(float)). Is this legal?
No, not to set the value of the float to 1.0f as the encoding of a float in not the bytes 1,1,1,1 @James Picone
memset(ptr,0,n*sizeof(float)) or better memset(ptr, 0, sizeof *ptr * n) will set every byte to 0. This is certainly the encoding for a float 0.0f.
To set every element of a float array to 1.0f or any value, simply use a loop.
float initial_value = 1.0f;
for (size_t i = 0; i < n; i++) {
ptr[i] = initial_value;
}
1 Comment
M.M
All bits zero is
0.0f in IEEE754, however the standard doesn't mandate such a representation
0x0is float zero, but0x01010101isn't 1, it's ~2.3*10**-38