Today while doing K&R question 1-19, a strange error (which I resolved) occurred in my for loop. The reason I am posting is to ask why this is the case.
K&R 1-19: Write a function reverse(s) that reverses the character string s . Use it to write a program that reverses its input a line at a time. My Solution:
#include <stdio.h>
int function1 (char []);
void reverse (char [], char[], int);
int main() {
char a[1000];
char b[1000];
int i;
i = function1(a);
reverse (b,a,i);
printf("%s",b);
putchar('\n');
return 0;
}
int function1 (char a[]) {
int i;
int p;
for (i=0; (i<1000-1) && (p=getchar())!=EOF && (p !='\n'); ++i) {
a[i]=p;
}
if (p == '\n') {
a[i]=p;
++i;
}
a[i]='\0';
return i;
}
void reverse (char a[], char b[], int c) {
int i;
int x;
i=0;
/*It appears that in the for declaration you must use , instead of && */
for (x=c-1; x>=0; (++i) && (x=x-1)) {
a[i] = b[x];
}
a[i+1]='\0';
}
My code successfully accomplishes the task (there are some garbage characters at the end but I will figure that out). However, I noticed that in the increment part of the for loop something strange happens:
Let's say I type:
hi my name is john
I will get:
nhoj si eman ym ih
Which is the correct response. However, if I reverse the increment portion:
for (x=c-1; x>=0; (x=x-1) && (++i)) {
Strangely, enough my output becomes:
nhoj si eman ym h
The second character (i) becomes missing. Why is this the case?