Search code examples
cstring-formattingprintf

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?

Solution

  • 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);