使用函数将LONG LONG INT转换为不带SPRINF的字符串 [英] Convert long long int to string without sprintf using functions
本文介绍了使用函数将LONG LONG INT转换为不带SPRINF的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
sprintf()
或ltoi()
。
问题是,当我返回值时,如果我在将值返回给调用函数之前没有在我的函数中printf()
,它就不会正确返回。
#include <stdio.h>
#include <stdlib.h>
char *myBuff;
char * loToString(unsigned long long int anInteger)
{
int flag = 0;
char str[128] = { 0 }; // large enough for an int even on 64-bit
int i = 126;
while (anInteger != 0) {
str[i--] = (anInteger % 10) + '0';
anInteger /= 10;
}
if (flag) str[i--] = '-';
myBuff = str+i+1;
return myBuff;
}
int main() {
// your code goes here
unsigned long long int d;
d= 17242913654266112;
char * buff = loToString(d);
printf("chu %s
",buff);
printf("chu %s
",buff);
return 0;
}
推荐答案
我修改了几个点
str
应动态分配或应在全局范围内。否则,其作用域将在loToString()
执行后结束,并且您将从str
数组返回地址。char *myBuff
移到本地作用域。两个都很好。但不需要在全球范围内声明。
检查修改后的代码。
char str[128]; // large enough for an int even on 64-bit, Moved to global scope
char * loToString(unsigned long long int anInteger)
{
int flag = 0;
int i = 126;
char *myBuff = NULL;
memset(str,0,sizeof(str));
while (anInteger != 0) {
str[i--] = (anInteger % 10) + '0';
anInteger /= 10;
}
if (flag) str[i--] = '-';
myBuff = str+i+1;
return myBuff;
}
这篇关于使用函数将LONG LONG INT转换为不带SPRINF的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文