c++ - Return char * instead of string -
i trying use 'user434507''s unsigned solution here:
c++ performance challenge: integer std::string conversion
but instead want return char * , not accept in string.
i have been playing around awhile , have got, returns nothing/garbage - limited c , pointer knowledge not helping me. think using malloc right, in original code it's if uses internal char* , changed elements of string , returns string. figured if allocated via malloc have same effect :
char * itostr(unsigned val) { const char digit_pairs[201] = { "00010203040506070809" "10111213141516171819" "20212223242526272829" "30313233343536373839" "40414243444546474849" "50515253545556575859" "60616263646566676869" "70717273747576777879" "80818283848586878889" "90919293949596979899" }; int size; if(val>=10000) { if(val>=10000000) { if(val>=1000000000) { size=10; } else if(val>=100000000) { size=9; } else { size=8; } } else { if(val>=1000000) { size=7; } else if(val>=100000) { size=6; } else { size=5; } } } else { if(val>=100) { if(val>=1000) { size=4; } else { size=3; } } else { if(val>=10) { size=2; } else { size=1; } } } char * c = (char *)malloc(size + 1); c[size] = '\0'; //char* c = &s[size-1]; while(val>=100) { int pos = val % 100; val /= 100; *(short*)(c-1)=*(short*)(digit_pairs+2*pos); c-=2; } while(val>0) { *c--='0' + (val % 10); val /= 10; } return c; }
c += size-1;
you need line before first while
loop. 2 loops write digits right left. it's needed writing starts @ right end of string.
Comments
Post a Comment