1

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.

3
  • 2
    That argument is the value to set each byte to, not each 32-bit word. 0x0 is float zero, but 0x01010101 isn't 1, it's ~2.3*10**-38 Commented Jun 27, 2018 at 2:32
  • So initialize with 0 values is okay, while 1 is dangerous? Commented Jun 27, 2018 at 3:11
  • 1
    no they're both safe and defined; it's just that you can't see an array of floats to 1 with memset; the interface doesn't support it. Commented Jun 27, 2018 at 3:17

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

All bits zero is 0.0f in IEEE754, however the standard doesn't mandate such a representation
2

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.