J’essaye de convertir un long long int non signé en chaîne sans utiliser aucune fonction de bibliothèque comme sprintf()
ou ltoi()
. Le problème est que lorsque je retourne la valeur, elle ne retourne pas correctement, si je ne fais pas printf()
dans ma fonction avant de la renvoyer à la fonction appelante.
#include #include char *myBuff; char * loToSsortingng(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 = loToSsortingng(d); printf("chu %s\n",buff); printf("chu %s\n",buff); return 0; }
J’ai modifié quelques points
str
doit être alloué dynamicment ou doit avoir une scope globale. sinon sa scope se terminera après l’exécution de loToSsortingng()
et vous retournerez une adresse à partir du tableau str
. char *myBuff
est déplacé dans la scope locale. Les deux vont bien. Mais pas besoin de le déclarer globalement. Vérifiez le code modifié.
char str[128]; // large enough for an int even on 64-bit, Moved to global scope char * loToSsortingng(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; }