使用函数将long long int转换为不带sprintf的字符串

时间:2017-03-22 04:21:37

标签: c string return-value

我试图将unsigned long long int转换为字符串而不使用任何库函数,如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\n",buff);
    printf("chu %s\n",buff);


    return 0;

}

1 个答案:

答案 0 :(得分:1)

我修改了几点

  • 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; 
    }