This is variation of one of exercises from Kernighan C book. Basically prints the longest line from standard input.
My question is, if looking at the 'copy method', how does the copy method actually work if it returns void. I'm coming from Java and learning C for the first time. In the copy method, the to and from char arrays are local. How do they actually get stored in longest and line variables in the main method if they are in no way returned back to main?
I am very confused...
Thanks very much for the time!
EDIT: THANK YOU FOR REPLIES. One more note... Oh. So you the author is passing the values with pointers. That is extremely confusing since the a page before it reads - "...in C the called function cannot directly alter a variable in the calling function; it can only alter its private, temporary copy." Is that correct? Second question is, how can I make these functions pass data around just like in Java, PHP and etc. Or is this something C programmers see as a benefit?
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
main () {
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = getline(line, MAXLINE)) > 0) {
if(len > max) {
max = len;
copy(longest, line);
}
}
if(max > 0) printf("%s", longest);
return 0;
}
int getline (char line[], int limit) {
int i, c;
for (i = 0; i < limit - 1 && (c = getchar()) != EOF && c != '\n'; i++) line[i] = c;
if (c == '\n') {
line[i] = c;
i++;
}
line[i] = '\0';
return i;
}
void copy(char to[], char from[]) {
int i;
i = 0;
while((to[i] = from[i]) != '\0') i++;
}