Reputation: 318
I am writing a bit of an operating system, and I require the ability to print the addition of a variable. I have a working atoi function and so I reversed it to give me an itoa function. There is no way to access free memory, so I need to figure out the the number of digits in order to create the proper sized char array. I figured I would need to divide by 10 to get that, and then modulus the values into the correct spot. This is my c code so far:
char* itoa(int res) {
int size = 0;
int t = res;
while(t / 10 != 0) {
t = t/10;
size ++;
}
char ret[size+1];
ret[size] = '\0';
t = res;
int i = size - 1;
while(i > 0) {
ret[i] = t % 10;
t = t/10;
i--;
}
return ret;
}
As of right now, it prints nothing. What is wrong with it?
Upvotes: 0
Views: 348
Reputation: 24857
If you can put up with the caller providing a buffer large enough for all expected outputs, then you can:
#include <stdio.h>
char * rIntToAscii(int num, char * result){
if( num == 0 ) return result;
else{
result=rIntToAscii( num/10, result );
*result = '0'+num%10;
return result+1;
}
};
void intToAscii(int num,char *output){
if (num==0){
*output++='0';
*output='\0';
}
else
{
if(num<0){
*output++='-';
num=-num;
};
*rIntToAscii(num, output) = '\0';
};
};
int main(void)
{
int test = -10;
char testOutput[ 32 ];
intToAscii(test,testOutput);
printf( "%s", testOutput );
return 0;
}
Upvotes: 1
Reputation: 15387
There are a lot of things wrong here. Most obviously:
ret
is on the stack and doesn't exist after popping.Put together, these basically kill your implementation. So, to be helpful, here's some untested code:
void putc(char c) {
/*Output "c" via BIOS interrupt or VGA write. Or whatever.*/
}
void print(int num) {
if (num!=0) {
/*Largest num is `2,147,483,64(7|8)`*/
char temp[10];
int i = 0;
if (num<0) { putc('-'); num=-num; }
if (num>0); else { temp[i++]='8'; num=-(num/10); } //signed wraparound
while (num>0) {
temp[i++] = num%10 + '0';
num /= 10;
}
while (--i>=0) putc(temp[i]);
} else putc('0');
}
Upvotes: 2
Reputation: 885
It has a few bugs. Here's a working version for positive numbers at least:
char* itoa(int res) {
int size = 0;
int t = res;
while(t / 10 != 0) {
t = t/10;
size++;
}
static char ret[64];
size++;
ret[size] = '\0';
t = res;
int i = size - 1;
while(i >= 0) {
ret[i] = (t % 10) + '0';
t = t/10;
i--;
}
return ret;
}
Upvotes: 3