gpt4 book ai didi

c - 在 C 中,如何在不使用 snprintf 或 itoa 的情况下将 int 转换为 char[]?

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:02 25 4
gpt4 key购买 nike

我的头发在这里拉出来,但我需要在不使用 snprintf 或 itoa 的情况下将 int 转换为 C 中的字符串。有什么建议吗?

我尝试使用:

/*
** LTOSTR.C -- routine and example program to convert a long int to
** the specified numeric base, from 2 to 36.
**
** Written by Thad Smith III, Boulder, CO. USA 9/06/91
** and contributed to the Public Domain.
**
** src: http://www8.cs.umu.se/~isak/snippets/ltostr.c
*/

#include <stdlib.h>

char * /* addr of terminating null */
ltostr (
char *str, /* output string */
long val, /* value to be converted */
unsigned base) /* conversion base */
{
ldiv_t r; /* result of val / base */

if (base > 36) /* no conversion if wrong base */
{
str = '\0';
return str;
}
if (val < 0) *str++ = '-';
r = ldiv (labs(val), base);

/* output digits of val/base first */

if (r.quot > 0) str = ltostr (str, r.quot, base);

/* output last digit */

*str++ = "0123456789abcdefghijklmnopqrstuvwxyz"[(int)r.rem];
*str = '\0';
return str;
}

...但它在 *str++ = "0123456789abcdefghijklmnopqrstuvwxyz"[(int)r.rem]; 上给了我一个 EXE_BAD_ACCESS。

最佳答案

我猜你没有分配任何内存。

str 需要是指向分配内存块的指针,该内存块足够大以容纳函数创建的字符串。

这个函数不分配任何内存。您需要在调用函数之前执行此操作,然后将指针传入。

关于c - 在 C 中,如何在不使用 snprintf 或 itoa 的情况下将 int 转换为 char[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6091719/

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