将int列表转换为字符串-C

发布于 2025-02-02 16:57:54 字数 408 浏览 4 评论 0原文

我试图将整数列表转换为紧凑的字符串,但我会得到一个分段故障。 代码如下:

    int *factors = job_factorization(number, size);
    char buffer[250] = { 0 };

    for (int i = 0; i < *size; i++) {
        sprintf( &buffer[i],  "%d ", *factors);
        factors++;
    }

job_factorization函数返回列表的头部(它有效,我已经对其进行了测试),它将指向size size指向的值设置为列表的实际大小(因此整数的数量)。 我不知道有什么问题,有人有任何想法吗?

I was trying to convert a list of integers into a compact string but I get a segmentation fault.
The code is the following:

    int *factors = job_factorization(number, size);
    char buffer[250] = { 0 };

    for (int i = 0; i < *size; i++) {
        sprintf( &buffer[i],  "%d ", *factors);
        factors++;
    }

The job_factorization function returns the head of the list (it works, I have already tested it), and it sets the value pointed to by size to the actual size of the list (so the number of integers).
I cannot figure out what is wrong, does anyone have any idea?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半﹌身腐败 2025-02-09 16:57:54

请注意以下备注:

  • sprintf(&amp; buffer [i],“%d”, *factor);在上一个转换结束时不会转换数字。

  • sprintf不检查缓冲区溢出:如果size足够大,它最终会在缓冲区的末端以外写入。

  • 修改因素可能不是一个好主意,因为使用后应释放此指针。

这是一种替代方法:

    int *factors = job_factorization(number, size);
    char buffer[1024];
    size_t pos = 0;

    for (int i = 0; pos < sizeof buffer && i < *size; i++) {
        pos += snprintf(buffer + pos, sizeof buffer - pos, "%d ", factors[i]);
    }

您还可以使用2个循环来计算转换所需的尺寸并分配所需的空间。

Note these remarks:

  • sprintf( &buffer[i], "%d ", *factors); does not convert the number at the end of the previous conversion.

  • sprintf does not check for buffer overflow: if size is large enough, it will eventually write beyond the end of the buffer.

  • modifying factors is probably not a good idea as this pointer should be freed after use.

Here is an alternative:

    int *factors = job_factorization(number, size);
    char buffer[1024];
    size_t pos = 0;

    for (int i = 0; pos < sizeof buffer && i < *size; i++) {
        pos += snprintf(buffer + pos, sizeof buffer - pos, "%d ", factors[i]);
    }

You could also use 2 loops to compute the size needed for the conversion and allocate the space needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文