确定的sprintf缓冲区大小 - 有什么标准呢? [英] Determining sprintf buffer size - what's the standard?

查看:562
本文介绍了确定的sprintf缓冲区大小 - 有什么标准呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在转换成int类型,像这样:

When converting an int like so:

char a[256];
sprintf(a, "%d", 132);

什么是确定多大的的应该是最好的方法是什么?我想手动设置它是好的(因为我已经看到了使用,随处可见),但它应该多大?什么是可能在32位系统上最大的int值,并有确定的飞行?

what's the best way to determine how large a should be? I assume manually setting it is fine (as I've seen it used everywhere), but how large should it be? What's the largest int value possible on a 32 bit system, and is there some tricky way of determining that on the fly?

推荐答案

在一个int位的最大可能的数量是 CHAR_BIT *的sizeof(INT),和一个十进制数字是身价至少3位,所以一个松散的上限为所需的空间任意 INT (CHAR_BIT *的sizeof(INT) / 3)+ 3 。这是+3之一,我们舍去分裂时,一个符号,一个用于NUL终止的事实。

The max possible number of bits in an int is CHAR_BIT * sizeof(int), and a decimal digit is "worth" at least 3 bits, so a loose upper bound on the space required for an arbitrary int is (CHAR_BIT * sizeof(int) / 3) + 3. That +3 is one for the fact that we rounded down when dividing, one for the sign, one for the nul terminator.

如果通过在32位系统上的你的意思是你知道 INT 是32位的,那么你就需要12个字节。 10数字,一个符号,一个用于NUL终止。

If by "on a 32 bit system" you mean that you know int is 32 bits, then you need 12 bytes. 10 for the digits, one for the sign, one for the nul terminator.

在特定的情况下,如果要转换的int是 132 ,则需要4个字节。 Badum,tish。

In your specific case, where the int to be converted is 132, you need 4 bytes. Badum, tish.

其中固定大小的缓冲器可以以合理的结合使用,它们是简单的选择。我不那么谦虚地提出了约束上面是合理的(13个字节,而不是12 32位 INT ,和23个字节,而不是21对64位 INT )。但对于困难的情况下,在C99中你可以只调用的snprintf 来获得尺寸,然后的malloc 那么多。这是矫枉过正这样一个简单的情况下这一点。

Where fixed-size buffers can be used with a reasonable bound, they are the simpler option. I not-so-humbly submit that the bound above is reasonable (13 bytes instead of 12 for 32 bit int, and 23 bytes instead of 21 for 64 bit int). But for difficult cases, in C99 you could just call snprintf to get the size, then malloc that much. That's overkill for such a simple case as this.

这篇关于确定的sprintf缓冲区大小 - 有什么标准呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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