简体   繁体   中英

initialize float-type array using memset

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.

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 init_value = 1.0f;
for (size_t i = 0; i < n; n++) {
   ptr[i] = init_value;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM