#include <stdio.h>
#define MAXLINE 100
int get_line(char line[], int maxline);
void copy(char to[], char from[]);
/*Prints longest input line*/
int main(){
int len; /*Current line length*/
int max; /*Maximum length so far*/
char line[MAXLINE]; /*Current input line*/
char longest[MAXLINE]; /*Longest line is saved here*/
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;
}
/*get_line: read a line into s, return length*/
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'*/
void copy (char to[], char from[]){
int i;
i = 0;
while((to[i] = from[i]) != '\0')
++i;
}
This code is from Section 1.9 of The C Programming Language, I'm trying to understand how it works. I'm not understanding how the scopes of the variables work. In the while loop the function get_line
is modifying the variable line
and the function copy
is modifying the variable longest
.
Shouldn't they be only in the scope of the function? I don't get why the functions is able to modify them in main