确定 sprintf 缓冲区大小

编程入门 行业动态 更新时间:2024-10-20 21:01:32
本文介绍了确定 sprintf 缓冲区大小 - 标准是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当像这样转换 int 时:

When converting an int like so:

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

确定a 应该有多大的最佳方法是什么?我认为手动设置它很好(因为我已经看到它在任何地方都使用过),但它应该有多大?在 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 个字节.坏蛋,tish.

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

固定大小的缓冲区可以在合理的范围内使用,它们是更简单的选择.我不太谦虚地认为,上面的界限是合理的(32 位 int 是 13 个字节而不是 12 个字节,64 位 int 是 23 个字节而不是 21 个字节).但是对于困难的情况,在 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 缓冲区大小

本文发布于:2023-10-09 06:08:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474910.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓冲区   大小   sprintf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!