First of all let me apologize for being so "green".
You must have been pretty fed up with newbish questions, but,
still I felt, that's the only place I could get a decent answer.
Haven't been able to solve the 1-19 exercise (page 31) from K&R book,
I decided, it's time to cheat, so I took peek at:
http://users.powernet.co.uk/eton/kandr2/krx119.html
Still I would not understand certain things, I will place the
code, with my comments as me trying to figure it out. Grep for "why".
#include <stdio.h>
#define MAX_LINE 1000
void discard_nl(char s[]);
int reverse(char s[]);
int getline(char s[], int lim);
/* inserts a "end-of-string" instead of \n; why do we need \0? */
void discard_nl(char s[])
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] == '\n')
s[i] = '\0';
/* replaces \n with \0 */
}
}
/* the reverse function itself */
int reverse(char s[])
{
char ch;
int i, j;
for(j = 0; s[j] != '\0'; j++) /* going through array \ */
{ /* indexes */
;
}
--j; /* what is it? why is the array one element less? */
for(i =0; i < j; i++)
{
ch = s[i]; /* storing each value in ch */
s[i] = s[j]; /* first value equals last value */
s[j] = ch; /* las value equals first (ch) value */
--j; /* shrinking the number of i < j to be
* checked */
}
return 0;
}
/* getline: all chars up to \n; \n and \0 inserted afterwords, why? */
int getline(char s[], int lim)
{
int c, i;
for(i = 0; i < lim -1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n')
s[i++] = c; /* or: s[i] = '\n'; ++i; */
s[i] = '\0'; /* inserting "end-of-string" \0 */
return i;
}
int main()
{
char line[MAX_LINE];
while(getline(line, MAX_LINE) > 0) /* changed it to MAX_LINE \ */
{ /* instead of "sizeof line" \ */
discard_nl(line); /* by me */
reverse(line);
printf("%s\n", line);
}
return 0;
}
Any added comments are welcome. I won't be disappointed if someone skips
the post. Thank you. -nabis