C语言 snprintf 和 sprintf 解释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7505500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
snprintf and sprintf explanation
提问by funnyCoder
can someone explain to me the output of this simple program :
有人可以向我解释这个简单程序的输出:
#include <stdio.h>
int main(int argc, char *argv[])
{
char charArray[1024] = "";
char charArrayAgain[1024] = "";
int number;
number = 2;
sprintf(charArray, "%d", number);
printf("charArray : %s\n", charArray);
snprintf(charArrayAgain, 1, "%d", number);
printf("charArrayAgain : %s\n", charArrayAgain);
return 0;
}
And the output is :
输出是:
./a.out
charArray : 2
charArrayAgain : // Why i don't have 2 here?
Thanks.
谢谢。
回答by Malcolm Box
Because snprintf needs space for the \0 terminator of the string. So if you tell it the buffer is 1 byte long, then there's no space for the '2'.
因为 snprintf 需要为字符串的 \0 终止符留出空间。因此,如果您告诉它缓冲区的长度为 1 个字节,那么“2”就没有空间了。
Try with snprintf(charArrayAgain, 2, "%d", number);
试试 snprintf(charArrayAgain, 2, "%d", number);
回答by Adam Maras
snprintf(charArrayAgain, 1, "%d", number);
// ^
You're specifying your maximum buffer size to be one byte. However, to store a single digit in a string, you must have twobytes (one for the digit, and one for the null terminator.)
您将最大缓冲区大小指定为一字节。但是,要在字符串中存储单个数字,您必须有两个字节(一个用于数字,一个用于空终止符。)
回答by Timo Geusch
You've told snprintfto only print a single character into the array, which is not enough to hold the string-converted number (that's one character) and the string terminator \0, which is a second character, so snprintf is not able to store the string into the buffer you've given it.
您已经告诉snprintf只将一个字符打印到数组中,这不足以保存字符串转换的数字(即一个字符)和字符串终止符 \0,即第二个字符,因此 snprintf 无法存储将字符串放入您提供的缓冲区中。
回答by Keith Thompson
The second argument to snprintfis the maximum number of bytes to be written to the array (charArrayAgain). It includes the terminating '\0', so with size of 1 it's not going to write an empty string.
to的第二个参数snprintf是要写入数组 ( charArrayAgain)的最大字节数。它包括终止'\0',所以大小为 1 它不会写一个空字符串。
回答by wildplasser
Check the return value from the snprintf() it will probably be 2.
检查 snprintf() 的返回值,它可能是 2。

