How to improve buffer size determination for printfing various integer types?

后端 未结 4 1154
萌比男神i
萌比男神i 2021-01-21 09:36

When converting an integer to text, typically I create a big buffer to use with sprintf() to hold any potential result.

char BigBuffer[50];         


        
4条回答
  •  萌比男神i
    2021-01-21 10:25

    asprintf() is handy, it takes a char ** and uses malloc() to get the needed space so you need to free() it later.

    No need to worry about how much space you need.

    int asprintf(char **ret, const char *format, ...); 
    
    char *p
    asprintf(&p, "%XXXX", ...); 
    :
    :
    free(p);
    

提交回复
热议问题