安全地将int转换为C中的字符串

标签 c string string-formatting unsigned

根据 top answer on SO,这是我应该在 C 中将整数转换为字符串的方法:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <math.h>

#define digits(x) ((int)((ceil(log10(abs(x)))+1)*sizeof(char)))

int main () {
    int a = 345908220;
    long b = 23094809284358;
    unsigned int c = 3456789234;
    uint8_t d = 242;
    int64_t e = -840958202029834;

    int dstr_len = digits(a) + digits(b) + digits(c) +
                   digits(d) + digits(e) + 5;

    char dstr[dstr_len];
    sprintf(dstr, "%d %ld %u %u %" PRIu64, a, b, c, d, e);

    printf("%s\n", dstr);

    return 0;
}

但是,这似乎效率低得离谱。我必须将我的程序链接到 libmath,并对我要打印的每个整数进行三个 数学调用。另请注意,我必须将 5 添加到我的缓冲区,而不仅仅是 1 用于 NUL 终止符,方法是计算格式中的空格数字符串。这似乎也容易出错,并可能导致缓冲区溢出。

那么,是否有任何好的标准函数可以为我计算缓冲区的大小?

我正在尝试编写安全的 C。

最佳答案

如果您的编译器有可用的snprintf(),您可以请求格式化的缓冲区长度,然后相应地进行分配:

int dstr_len = snprintf(NULL, 0, "%d %ld %u %u %" PRIu64, a, b, c, d, e) + 1;

char dstr[dstr_len];
//
// NOTE: variable-length arrays are NOT supported in all compilers!
// A more portable solution is:
//
// char *dstr = malloc(sizeof(char) * dstr_len);

snprintf(dstr, dstr_len, "%d %ld %u %u %" PRIu64, a, b, c, d, e);

// free(dstr);

关于安全地将int转换为C中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25691227/

相关文章:

求平均值的C程序,代码有什么问题?

iphone - 从 NSData 读取 NSNumber

arrays - Swift Alamofire 将值赋给字符串

excel - 如何使用 powershell 在整个 Excel 工作簿中搜索特定字符串

c++ - 为什么用 %20 程序崩溃替换空格?

C++ printf 带 %f 但已针对用户所在国家/地区进行了本地化

C++ 格式化字符串宏

c - 除了 umask 还有什么影响新目录的权限?

c - 在一台服务器上接收多个客户端数据包