16

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?

6 Answers 6

33

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

Sign up to request clarification or add additional context in comments.

2 Comments

How about instead of 2, you do sizeof(charArrayAgain).
agreed, sizeof(charArrayAgain) would be better - although often you have a pointer rather than an array, in which case sizeof() isn't going to work.
6
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.)

Comments

4

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.

Comments

4

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.

Comments

2

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

1 Comment

The return value should be 1
0

Directly from the cplusplus Documentation

snprintf composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by s (taking n as the maximum buffer capacity to fill).

If the resulting string would be longer than n-1 characters, the remaining characters are discarded and not stored, but counted for the value returned by the function.

A terminating null character is automatically appended after the content written.

After the format parameter, the function expects at least as many additional arguments as needed for format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.