I strongly recommend to avoid K&R since it teaches bad style and is very much outdated. This review will focus on general C programming rather than commenting on your specific algorithm.
Invalid C
main()
is an incorrect signature, this style went obsolete 23 years ago. You must useint main (void)
.
Bugs
for (i = j = 0; ...
thens1[i-1]
. This accessess1
out of bounds at the first lap of the loop.
Dangerous practice
char s1[MAXLINE], s2[MAXLINE];
it's not a good idea to allocate arrays of thousands of bytes in local scope - these will end up on the stack and eventually you risk stack overflow. Declaring them asstatic char s1[MAXLINE]
would have avoided that.- Incrementing/decrementing loop iterators anywhere else but in the third clause of a
for
loop is poor and dangerous practice, the code turns completely unreadable when you do. You should reconsider writing this loop differently, as close to the idiomaticfor(int i=0; s1[i]!='\0'; i++)
as possible. - Assignment inside conditions such as
c=getchar()
inside the 2ndfor
clause is bad style. K&R does this a lot but it's universally regarded as bad and bug-prone, why all mainstream compilers force an additional parenthesis when you do.
Poor style
- Avoid declaring multiple variables on a single line, it is harder to read and you can get subtle bugs that way too. Instead, declare each variable on a line of its own.
- Loop iterators should be declared inside the for loop clause 1 whenever possible - K&R is completely outdated here. That is
for(int i=0; ...
. s1
isn't modified by the expand function so that function should be written with const correctness:void expand (const char s1[], char s2[])
valid
should ideally have been declared asbool
.