Scope of variables in C, why is function modyfing values in main?

Viewed 62
#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

1 Answers

Array's names are actually a pointer to first element.
What [] operator does is same as *(array + n)

Edit: As pointed out in the comments, this might be confusing and misleading.
I recommend you taking a look at this question: Is an array name a pointer?

int a[10];
a[1] == *(a + 1) // true

get_line() and copy() has parameter type of char[], which is same as char*.
You passed memory address of line and longest to those functions.

Variables aren't completely inaccessible when out of scope,
you just can't reference them directly using names.
Normally function parameters are copy of original value passed to the function,
so changing them won't affect the original varaible.

But in this case you're passing memory address of a variable, and those functions are able to change value of array's elements through pointer.

Related