I am following K&R second edition examples to learn C and coding as I think this is correct way of doing things. Anyhow when I run this program post compilation the program get stuck. I used valgrind for execution of compiled script.
#include <ctype.h>
int atoi(char s[])
{
int i, n, sign;
for(i = 0; isspace(s[i]); i++)
;
sign = (s[i] == '-')? -1 : 1;
if (s[i] == '+'|| s[i] == '-')
i++;
for (int n = 0; isdigit(s[i]); n++)
n = 10 * n + (s[i]-'0');
return sign * n;
}
int main()
{
char input[] = " -12345";
atoi(input);
}
# vaibhavchauhan at startup001 in ~/Documents/Projects/K-R on git:master x [0:43:36]
$ valgrind ./atoi-general
==8075== Memcheck, a memory error detector
==8075== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==8075== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==8075== Command: ./atoi-general
==8075==
^C==8075==
In your second loop, you are iterating n
but you use i
for your computations and computations. This leads to the infinite loop you observe. To fix this, use either i
as an index consistently:
int atoi(char s[])
{
int i, sign, n;
for(i = 0; isspace(s[i]); i++)
;
sign = (s[i] == '-')? -1 : 1;
if (s[i] == '+'|| s[i] == '-')
i++;
for (n = 0; isdigit(s[i]); i++)
n = 10 * n + (s[i]-'0');
return sign * n;
}
Note that indices should have type size_t
, not int
as the latter might be not large enough to index every array. For this purpose, an index of type int
is fine though.