Size of formatted string





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















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] %03dt" 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










share|improve this question

























  • The size you provide as the second argument is the size of the buffer that snprintf will write the text into. And there's a "trick" to get to know the amount of characters needed by using snprintf itself (hint: what does it return?). Please see e.g. this printf (and family) reference for details.

    – Some programmer dude
    Nov 23 '18 at 13:46








  • 3





    By the way, sizeof(int) gives you the size of an int, not the number of digits it can hold.

    – Some programmer dude
    Nov 23 '18 at 13:47


















0















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] %03dt" 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










share|improve this question

























  • The size you provide as the second argument is the size of the buffer that snprintf will write the text into. And there's a "trick" to get to know the amount of characters needed by using snprintf itself (hint: what does it return?). Please see e.g. this printf (and family) reference for details.

    – Some programmer dude
    Nov 23 '18 at 13:46








  • 3





    By the way, sizeof(int) gives you the size of an int, not the number of digits it can hold.

    – Some programmer dude
    Nov 23 '18 at 13:47














0












0








0








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] %03dt" 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










share|improve this question
















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] %03dt" 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







c printf sizeof






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 15:52









Stoogy

761825




761825










asked Nov 23 '18 at 13:42









wolverinewolverine

345




345













  • The size you provide as the second argument is the size of the buffer that snprintf will write the text into. And there's a "trick" to get to know the amount of characters needed by using snprintf itself (hint: what does it return?). Please see e.g. this printf (and family) reference for details.

    – Some programmer dude
    Nov 23 '18 at 13:46








  • 3





    By the way, sizeof(int) gives you the size of an int, not the number of digits it can hold.

    – Some programmer dude
    Nov 23 '18 at 13:47



















  • The size you provide as the second argument is the size of the buffer that snprintf will write the text into. And there's a "trick" to get to know the amount of characters needed by using snprintf itself (hint: what does it return?). Please see e.g. this printf (and family) reference for details.

    – Some programmer dude
    Nov 23 '18 at 13:46








  • 3





    By the way, sizeof(int) gives you the size of an int, not the number of digits it can hold.

    – Some programmer dude
    Nov 23 '18 at 13:47

















The size you provide as the second argument is the size of the buffer that snprintf will write the text into. And there's a "trick" to get to know the amount of characters needed by using snprintf itself (hint: what does it return?). Please see e.g. this printf (and family) reference for details.

– Some programmer dude
Nov 23 '18 at 13:46







The size you provide as the second argument is the size of the buffer that snprintf will write the text into. And there's a "trick" to get to know the amount of characters needed by using snprintf itself (hint: what does it return?). Please see e.g. this printf (and family) reference for details.

– Some programmer dude
Nov 23 '18 at 13:46






3




3





By the way, sizeof(int) gives you the size of an int, not the number of digits it can hold.

– Some programmer dude
Nov 23 '18 at 13:47





By the way, sizeof(int) gives you the size of an int, not the number of digits it can hold.

– Some programmer dude
Nov 23 '18 at 13:47












3 Answers
3






active

oldest

votes


















2














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] %03dt", 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.






share|improve this answer

































    2














    Pass 0 and NULL first to obtain an exact amount



    int n = snprintf(NULL, 0, "[%02d] %03dt", i, k);


    Then you know you need n + 1



    char *buf = malloc(n + 1);
    snprintf(buf, n + 1, "[%02d] %03dt", i, k);
    free(buf);


    See it on ideone: https://ideone.com/pt0cOQ






    share|improve this answer

































      2














      n is the size of the string you're passing into snprintf, so it knows when to stop writing to the buffer. This is to prevent a category of errors knows as buffer overflows. snprintf will write n - 1 characters into the passed-in buffer and then terminate it with the null character.






      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447832%2fsize-of-formatted-string%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        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] %03dt", 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.






        share|improve this answer






























          2














          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] %03dt", 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.






          share|improve this answer




























            2












            2








            2







            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] %03dt", 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.






            share|improve this answer















            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] %03dt", 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.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 23 '18 at 13:54

























            answered Nov 23 '18 at 13:48









            BlazeBlaze

            7,5241832




            7,5241832

























                2














                Pass 0 and NULL first to obtain an exact amount



                int n = snprintf(NULL, 0, "[%02d] %03dt", i, k);


                Then you know you need n + 1



                char *buf = malloc(n + 1);
                snprintf(buf, n + 1, "[%02d] %03dt", i, k);
                free(buf);


                See it on ideone: https://ideone.com/pt0cOQ






                share|improve this answer






























                  2














                  Pass 0 and NULL first to obtain an exact amount



                  int n = snprintf(NULL, 0, "[%02d] %03dt", i, k);


                  Then you know you need n + 1



                  char *buf = malloc(n + 1);
                  snprintf(buf, n + 1, "[%02d] %03dt", i, k);
                  free(buf);


                  See it on ideone: https://ideone.com/pt0cOQ






                  share|improve this answer




























                    2












                    2








                    2







                    Pass 0 and NULL first to obtain an exact amount



                    int n = snprintf(NULL, 0, "[%02d] %03dt", i, k);


                    Then you know you need n + 1



                    char *buf = malloc(n + 1);
                    snprintf(buf, n + 1, "[%02d] %03dt", i, k);
                    free(buf);


                    See it on ideone: https://ideone.com/pt0cOQ






                    share|improve this answer















                    Pass 0 and NULL first to obtain an exact amount



                    int n = snprintf(NULL, 0, "[%02d] %03dt", i, k);


                    Then you know you need n + 1



                    char *buf = malloc(n + 1);
                    snprintf(buf, n + 1, "[%02d] %03dt", i, k);
                    free(buf);


                    See it on ideone: https://ideone.com/pt0cOQ







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 23 '18 at 13:51

























                    answered Nov 23 '18 at 13:46









                    pmgpmg

                    84.8k999170




                    84.8k999170























                        2














                        n is the size of the string you're passing into snprintf, so it knows when to stop writing to the buffer. This is to prevent a category of errors knows as buffer overflows. snprintf will write n - 1 characters into the passed-in buffer and then terminate it with the null character.






                        share|improve this answer




























                          2














                          n is the size of the string you're passing into snprintf, so it knows when to stop writing to the buffer. This is to prevent a category of errors knows as buffer overflows. snprintf will write n - 1 characters into the passed-in buffer and then terminate it with the null character.






                          share|improve this answer


























                            2












                            2








                            2







                            n is the size of the string you're passing into snprintf, so it knows when to stop writing to the buffer. This is to prevent a category of errors knows as buffer overflows. snprintf will write n - 1 characters into the passed-in buffer and then terminate it with the null character.






                            share|improve this answer













                            n is the size of the string you're passing into snprintf, so it knows when to stop writing to the buffer. This is to prevent a category of errors knows as buffer overflows. snprintf will write n - 1 characters into the passed-in buffer and then terminate it with the null character.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 23 '18 at 13:51









                            mnisticmnistic

                            7,21611025




                            7,21611025






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447832%2fsize-of-formatted-string%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Xamarin.form Move up view when keyboard appear

                                Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                Anylogic : not able to use stopDelay()