开发者

snprintf and sprintf explanation

Can someone explain 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;
}

The output is:

./a.out 
charArray : 2
charArrayAgain : // Why isn't there a 2 here?


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'.

Try with snprintf(charArrayAgain, 2, "%d", number);


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 two bytes (one for the digit, and one for the null terminator.)


You've told snprintf to 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.


The second argument to snprintf is 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.


Check the return value from the snprintf() it will probably be 2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜