C语言 使用函数将长整型转换为字符串,而不使用 sprintf



我正在尝试将无符号的长整形转换为字符串,而无需使用任何库函数,如 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 %sn",buff);
    printf("chu %sn",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; 
    }

最新更新