Search code examples
cprintfsizeof

Size of formatted string


I am struggling to understand what happens during snprintf. Let's say I have two numbers:

int i =11; int k = 3;

I want to format them like this "[%02d] %03d\t" and use snprintf. Afterwards I use the resulting string with write().

snprintf needs the length/bytes n. I do not understand what is the length I need to provide... I have 2 theories:

a) It is

sizeof(int)*2

b) I check how many chars the formatted string will contain by counting the digits of the two integers and adding the other chars that the output will have:

2*sizeof(char) + 1*sizeof(char) + 2*sizeof(char) + 3*sizeof(char)+ 1*sizeof(char)

-> digits of i + digits of k + zeros added to first int + zeros added to second int + tab

I am struggling to understand what is the "n" I have to give to snprintf


Solution

  • It is the buffer size

    According to a documentation:

    Maximum number of bytes to be used in the buffer. The generated string has a length of at most n-1, leaving space for the additional terminating null character. size_t is an unsigned integral type.

    Suppose you write to an array such as this:

    char buf[32];
    

    The buffer can hold 32 chars (including the null terminator). Therefore we call the function like this:

    snprintf (buf, 32, "[%02d] %03d\t", i, k); 
    

    You can also check the return value to see how many chars have been written (or would have been written). In this case, if it's bigger than 32, then that would mean that some characters had to be discarded because they didn't fit.