Is there a better way to size a buffer for printing integers?

后端 未结 5 610
执笔经年
执笔经年 2021-01-16 01:41

I want to create a buffer for sprintfing a integer (in this case an unsigned int). A simple and misguided approach would be:

char b         


        
5条回答
  •  再見小時候
    2021-01-16 02:33

    If you're OK with dynamically allocated memory, you can use asprintf instead. This function will allocate the proper amount of memory to hold the string.

    char *buf;
    int result = asprintf(&buf, "%u", x);
    if (result == -1) {
        perror("asprintf failed");
    } else {
        ...
        free(buf);
    }
    

提交回复
热议问题