diff options
| author | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-12-04 08:46:22 +0800 |
|---|---|---|
| committer | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-12-04 08:46:22 +0800 |
| commit | 1d958679201f143ecf1c5527bd462e29b87427de (patch) | |
| tree | 08781740462e1d183f48d63ed8cc6ae1800a6853 /3 | |
| parent | 8e6cbc215e31bfd016a392d992e2b9a74da20580 (diff) | |
| download | k&r-exercises-1d958679201f143ecf1c5527bd462e29b87427de.tar.gz | |
3.4
Diffstat (limited to '3')
| -rw-r--r-- | 3/4.c | 10 |
1 files changed, 4 insertions, 6 deletions
@@ -4,14 +4,10 @@ #define MAXLEN 50 -// xplanation of the error: -// In itoa, for largest negative number, n = -n overflows -// resulting in n = INT_MIN (wraps around) causing a god awful mess. - void itoa(int n, char s[]); void reverse(char s[]); -/* Fixes itoa function to handle the largest negative number */ +/* fixes itoa function to handle the largest negative number */ int main(int argc, char *argv[]) { char s[MAXLEN]; @@ -27,12 +23,14 @@ void itoa(int n, char s[]) { i = 0; - if (n != INT_MIN) { + if (n >= 0) { do { s[i++] = n % 10 + '0'; } while ((n /= 10) > 0); } else { + // avoid integer overflow of n = -n of min n in original impl + // by handling negtive values separately. do { s[i++] = -(n % 10) + '0'; } while ((n /= 10) <= -1); |
