动态分配和设置为零flo​​at数组 [英] Dynamically allocating and setting to zero an array of floats

查看:163
本文介绍了动态分配和设置为零flo​​at数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何分配过程中自动设置浮标动态分配的数组为零(0.0)

How do I automatically set a dynamically allocated array of floats to zero(0.0) during allocation

这是确定

float* delay_line = new float[filter_len];

//THIS
memset(delay_line, 0.0, filter_len); //can I do this for a float??

//OR THIS
for (int i = 0; i < filter_len; i++)
  delay_line[i] = 0.0;

这是最有效的方式。

Which is the most efficient way

感谢

推荐答案

使用的sizeof(浮动)* filter_len ,除非你是在一些奇怪的实施工作,其中的sizeof(浮点)==的sizeof(char)的

Use sizeof(float) * filter_len unless you are working in some odd implementation where sizeof(float) == sizeof(char).

memset(delay_line, 0, sizeof(float) * filter_len);

编辑: Stephan202 在评论中指出的,0.0是一个特别容易的浮点值code对于memset的,因为对于0.0的IEEE标准重新presentation是全零位。

As Stephan202 points out in the comments, 0.0 is a particularly easy floating point value to code for memset since the IEEE standard representation for 0.0 is all zero bits.

memset的是在记忆的境界,而不是数字的境界运行。第二个参数,宣告一个int,强制转换为无符号的字符。如果你的C ++的实现使用每个浮四个字节,以下关系:

memset is operating in the realm of memory, not the realm of numbers. The second parameter, declared an int, is cast to an unsigned char. If your implementation of C++ uses four bytes per float, the following relationships hold:


  • 如果您memset的浮球随0,则该值将是0.0。

  • 如果您memset的浮球随1,该值将是2.36943e-38。

  • 如果您memset的浮动与42,值将是1.51137e-13。

  • 如果您memset的浮子64,该值将是3.00392。

所以零是一种特殊情况。

So zero is a special case.

如果这看起来奇怪,记得memset的是上述&lt声明; CString的&GT;或所述; string.h中&gt;和通常用于制造像***************或--------------- ---。它可以的的使用零内存是一个极好的副作用。

If this seems peculiar, recall that memset is declared in <cstring> or <string.h>, and is often used for making things like "***************" or "------------------". That it can also be used to zero memory is a nifty side-effect.

米兰Babuškov在评论中指出,有一个函数bzero(非标准德precated),可用于在Mac和Linux,但不是微软,它,因为它是专门针对设置内存的时刻零,安全地省略了一些指令。如果你使用它,你的编译器的清教徒将来的版本中忽略它,它是微不足道bzero自己实现本地兼容性补丁,除非将来的版本拥有的用于其它目的重新使用的名称

As Milan Babuškov points out in the comments, there is a function bzero (nonstandard and deprecated), available for the moment on Mac and Linux but not Microsoft, which, because it is specially tailored to setting memory to zero, safely omits a few instructions. If you use it, and a puritanical future release of your compiler omits it, it is trivial to implement bzero yourself in a local compatibility patch, unless the future release has re-used the name for some other purpose.

这篇关于动态分配和设置为零flo​​at数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆