Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 260
funnyCoder Avatar asked Sep 21 '11 19:09

funnyCoder


People also ask

What is difference between sprintf and Snprintf?

The snprintf function is similar to sprintf , except that the size argument specifies the maximum number of characters to produce. The trailing null character is counted towards this limit, so you should allocate at least size characters for the string s .

What is Snprintf used for?

The snprintf is a predefined library function of the stdio. h header file, which redirects the output of the standard printf() function to other buffers. The snprint() function is used to format the given strings into a series of characters or values in the buffer area.

What is meant by sprintf?

sprintf stands for "string print". In C programming language, it is a file handling function that is used to send formatted output to the string. Instead of printing on console, sprintf() function stores the output on char buffer that is specified in sprintf.

Where is Snprintf defined in C?

The snprintf() function is defined in the <stdio. h> header file and is used to store the specified string till a specified length in the specified format. Characteristics of snprintf() method: The snprintf() function formats and stores a series of characters and values in the array buffer.


1 Answers

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

like image 119
Malcolm Box Avatar answered Oct 01 '22 18:10

Malcolm Box