memset(ary,0,length) 是一种在双精度数组中输入零的便携式方法
以下代码使用 memset 将所有位设置为零
int length = 5;
double *array = (double *) malloc(sizeof(double)*length);
memset(array,0,sizeof(double)*length);
for(int i=0;i<length;i++)
if(array[i]!=0.0)
fprintf(stderr,"not zero in: %d",i);
我可以假设这适用于所有平台吗?
double 数据类型是否始终符合 ieee-754 标准?
感谢您的回复, 并感谢 ::fill 模板命令。但我的问题更多是在双数据类型的意义上。
也许我应该为纯c 写下我的问题。 但无论如何还是谢谢你。
编辑:将代码和标签更改为 c
Possible Duplicate:
What is faster/prefered memset or for loop to zero out an array of doubles
The following code uses memset to set all the bits to zero
int length = 5;
double *array = (double *) malloc(sizeof(double)*length);
memset(array,0,sizeof(double)*length);
for(int i=0;i<length;i++)
if(array[i]!=0.0)
fprintf(stderr,"not zero in: %d",i);
Can I assume that this will work on all platforms?
Does the double datatype always correspond to the ieee-754 standard?
thanks for your replies,
and thanks for the ::fill template command. But my question was more in the sense of the double datatype.
Maybe I should have written my question for pure c.
But thanks anyway.
EDIT: changed code and tag to c
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您处于 C99 环境中,则无法得到任何保证。浮点数的表示在第 5.2.4.2.2 节中定义,但这只是逻辑、数学表示。该部分甚至没有提到浮点数如何以字节为单位存储。相反,它在脚注中说:
此外,第 6.2.6.1 条规定:
在该子条款的其余部分中,没有提到浮点类型。
总之,不能保证
0.0
表示为全位零。If you are in a C99 environment, you get no guarantee whatsoever. The representation of floating point numbers is defined in § 5.2.4.2.2, but that is only the logical, mathematical representation. That section does not even mention how floating point numbers are stored in terms of bytes. Instead, it says in a footnote:
Further, § 6.2.6.1 says:
And in the rest of that subclause, floating point types are not mentioned.
In summary, there is no guarantee that a
0.0
is represented as all-bits-zero.使用
::std::fill(array, array+length, 0.0);
Use
::std::fill(array, array+length, 0.0);
它不便携。只需使用循环即可。
您不需要强制转换 malloc 返回值。
It's not portable. Just use loop.
You don't need to cast malloc return value.