0

I am trying to convert an unsigned long long int to a string without using any library functions like sprintf() or ltoi(). The problem is that when I return the value it doesn't return correctly, if I do not printf() in my function before returning it to the calling function.

#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;

}
jjm
  • 431
  • 3
  • 19

1 Answers1

1

I modified few points

  • str should be allocated dynamically or should be in global scope. otherwise its scope will end after execution of loToString() and you are returning an address from str array.
  • char *myBuff is moved into local scope. Both is fine. But no need to declare it globally.

Check the modified code.

    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; 
    }
jjm
  • 431
  • 3
  • 19