Hi,
I am new to C and I have a very basic question regarding the example in paragraph 1.9 of K&R (reproduced below).
I managed to run the program through the Terminal of my Mac, but I do not understand how it works. Especially, I do not understand how the program captured my input and fed it as an argument to the getline_kr function. Indeed, I do not see the array line being assigned to a value anywhere. I would have expected a statement akin to the raw_input() function in Python.
Could anyone explain how the text that I type in the terminal after the program is launched ends up being assigned to the line array????
Thank you for your help.
Code:
#include <stdio.h>
#define MAXLINE 1000
int getline_kr(char line[], int maxline);
void copy(char to[], char from[]);
int main(void)
{
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len = getline_kr(line, MAXLINE)) > 0) /* QUESTION: WHERE IS LINE ASSIGNED A VALUE??????? */
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
/* getline: read a line into s, return length */
int getline_kr(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;
++i;
}
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume its big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}