Created
March 11, 2011 07:50
-
-
Save radiofreejohn/865590 to your computer and use it in GitHub Desktop.
K&R exercise 4-12, recursive itoa attempt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <limits.h> | |
// K&R 4-12 | |
// char *rita seems OK too but I don't want to return a char to the original caller | |
// not sure if this is bad practice. | |
// will overflow if integer is longer than the target array (which shouldn't happen) | |
void *rita(char *target, long source) | |
{ | |
// target is the pointer to the first location | |
// i want to fill that location with the value of the lowest order digit | |
// then increment the pointer and add the next digit | |
// then finish by adding \0 | |
// first check that number does not misbehave | |
unsigned long m; | |
// thanks C Interfaces and Implementations for pointing out this edge case. | |
if (source == LONG_MIN) | |
{ | |
m = LONG_MAX + 1UL; | |
} else if (source < 0) { | |
m = -source; | |
} else { | |
m = source; | |
} | |
if (source < 0) | |
*target++ = '-'; | |
if (source/10) | |
target = rita(target, m/10); | |
// I pass target and the reduced integer | |
// then return the incremented target. | |
// The deepest value of target is the first pointer to the char array | |
// then it increments it as it passes it down the line (*++target = '\0';) | |
// it also fills the upcoming character with a terminator, it may be replaced | |
// by a digit, if not, it remains terminated | |
*target = m % 10 + '0'; | |
*++target = '\0'; | |
return target; | |
} | |
int main() | |
{ | |
long a = LONG_MIN; | |
char myval[21]; | |
rita(myval, a); | |
printf("%s\n", myval); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment