snprintf and sprintf explanation
Asked Answered
M

6

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?
Mysia answered 21/9, 2011 at 19:27 Comment(0)
R
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);

Reisinger answered 21/9, 2011 at 19:31 Comment(2)
How about instead of 2, you do sizeof(charArrayAgain).Birddog
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.Reisinger
S
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.)

Stamford answered 21/9, 2011 at 19:31 Comment(0)
P
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.

Pushkin answered 21/9, 2011 at 19:34 Comment(0)
B
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.

Blepharitis answered 21/9, 2011 at 19:35 Comment(0)
P
2

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

Potence answered 21/9, 2011 at 19:31 Comment(1)
The return value should be 1Amyotonia
E
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.

Eskill answered 28/6, 2024 at 17:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.