Hmmm, ok. Let me make some adjustments.
char* itoa(int val, int base)
{
new static char* buf[32] = {0}; //1
//since base can only be octal, decimal or hex
if (base != 8 && base != 10 && base != 16) //2
printf("Not a valid base.");
for(int i=30; val && i; --i)
{
val /= base;
buf[i] = "0123456789abcdef"[val % base]; //3
}
if(value == 0)
//return char 0 //4
if(value < 0 && base == 10)
//make the output negative //5
return &buf[i+1];
}
1. So 'new' here will work? This will allocate the return value on behalf of the caller?
I was worried that if two consecutive itoa() calls were made, and then they were both output, that the first one would be overridden.
2. LOL, duh, stupid mistake. Thanks vmanes.
3. And actually, could someone please explain
buf[i] = "0123456789abcdef"[val % base]; to me. I found the trick somewhere else, and kind of understand how it works, but I don't exactly understand HOW it works, if you know what I mean.
WaltP, why would you avoid this trick?
4. With the code the way it is, wouldn't I need a special case to account for a value of 0? Otherwise it won't even run the for loop. Additionally, how should a return a char 0?
5. I'm not sure how to make the output negative here exactly.
--
Watch your index usage. You start out with array of 36 elements, your processing loop starts at index 30. Pick a size! Remember that last valid index is size-1, and that position better contain a NULL terminator for the string.
I changed the array of elements to be 32. This should solve both issues, right?
I do find it a bit problematic that you will return the address of a point inside the block of memory allocated, thus orphaning the memory at the beginning of that block.
How would I go about correcting these issues? I'd really like this implementation to be functional as well as optimally efficient.
---
I was getting frustrated with this implementation I was trying above, so I started working on something much much more basic, and therefore probably a lot less efficient, and no doubt soon to be full of problems as well, but seeing your guys' posts here makes me want to make sure this implementation works moreso than the new one I was going to get at. So please bare with me as I try to get the final function for my code.