C
ceo
Hi,
I picked up the itoa example code from K&R and am trying to modify it
to as per these conditions:
1) input integer is always +ve
2) cannot assume the length of the integer parameter
Following is the modified code, please comment.
Thanks,
ceo
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* my_itoa: convert n to string */
char* my_itoa(unsigned int n) {
int i=0,c=0,j=0;
char *s = NULL;
do {
s = (char *) realloc(s, (i+1)*sizeof( char));
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
s = (char *) realloc(s, i*sizeof( char));
s = '\0';
for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
c = s;
s = s[j];
s[j] = c;
}
return s;
}
int main(int agrv, char *argv) {
char *p = NULL;
p = my_itoa(23456);
printf("(%s)\n", p);
if(!p) free(p);
return 0;
}
I picked up the itoa example code from K&R and am trying to modify it
to as per these conditions:
1) input integer is always +ve
2) cannot assume the length of the integer parameter
Following is the modified code, please comment.
Thanks,
ceo
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* my_itoa: convert n to string */
char* my_itoa(unsigned int n) {
int i=0,c=0,j=0;
char *s = NULL;
do {
s = (char *) realloc(s, (i+1)*sizeof( char));
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
s = (char *) realloc(s, i*sizeof( char));
s = '\0';
for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
c = s;
s = s[j];
s[j] = c;
}
return s;
}
int main(int agrv, char *argv) {
char *p = NULL;
p = my_itoa(23456);
printf("(%s)\n", p);
if(!p) free(p);
return 0;
}