Hello everyone,
I am new to C and am currently working through the book "The C Programming Language" by Kernighan and Ritchie.
The following code example, found on page 30, gets lines of inputs from the user, determines which line is the longest, and then prints the longest line.
I have tested this code and it seems to work as intended.
My question is regarding the function "copy" which receives two arrays of characters and copies one array to the other. I am wondering how this new array ends up being stored in the array "longest" found in the main function. There is no return type of the function, so it is not returned and it is my understanding that arguments in C are value not reference. So, what is happening here? Any explanation would be appreciated. Thanks!
Code:
#include <stdio.h>
#define MAXLINE 1000
int get_line(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 = get_line(line, MAXLINE)) > 0)
if(len > max) {
max = len;
copy(longest, line);
}
if(max > 0)
printf("%s", longest);
return 0;
}
/*getline: read a line into s, return lenght*/
int get_line(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 to is big enough */
void copy(char to[], char from[]){
int i;
i = 0;
while((to[i] = from[i]) != '\0')
++i;
}