Reputation: 13
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.
Upvotes: 1
Views: 4136
Reputation: 153303
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;
}
Upvotes: 3
Reputation: 249093
Initializing floats to all-bytes-zero is OK (it will produce float 0.0). But all-bytes-1 is not reasonable, because it will produce a "garbage" value (but the same value every time).
Upvotes: 2