gpt4 book ai didi

c - C 中的整数到字符串,无需预先分配字符数组

转载 作者:行者123 更新时间:2023-11-30 14:30:03 27 4
gpt4 key购买 nike

请看下面的代码,它只是将 unsigned int 转换为字符串(可能有一些未处理的情况,但这不是我的问题),在堆中分配一个 char 数组并返回它,让用户有责任使用后将其释放。你能解释一下为什么 C 标准库中不存在这样的函数(和其他类似的函数)吗?是的,printf("%s\n", itos(5)) 是一个内存泄漏,但这种编程模式已经被使用,并且被认为是一个很好的实践[1]。 IMO,如果这样的函数自 C 诞生以来就已经存在,我们将不会有更多的内存泄漏,但的缓冲区溢出会更少!

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

char* itos(unsigned int value)
{
int string_l = (value == 0) ? 1 : (int)log10(value) + 1;
char *string = malloc((string_l + 1) * sizeof(char));
int residual = value;
int it;
for (it = string_l - 1; it >= 0; it--) {
int digit;
digit = residual % 10;
residual = residual / 10;
string[it] = '0' + digit;
}
string[string_l] = '\0';
return string;
}

int main(void)
{
char* string = itos(534534345);
printf("%s\n", string);
free(string);
return 0;
}

[1] http://www.opengroup.org/onlinepubs/009695399/functions/getaddrinfo.html

编辑:

哈比的回答:

char *string;
asprintf(&string, "%d", 155);
printf("%s\n", string);
free(string);

最佳答案

事实证明 asprintf 正是您所需要的:)

关于c - C 中的整数到字符串,无需预先分配字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3832844/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com