Search code examples
ckernighan-and-ritchie

Call by reference behavior when calling by value


I am working through chapter 1.9 of the K&R C book and I don't fully understand the example code given. In it, there is a function getline(line, MAXLINE) that returns an int of the length of a line.

However, right afterwards, the 'line' variable is used. From my understanding of functions, the line variable should not be modified and C is just passing line and MAXLINE to the function and the function returns the length of a line. This looks like a pass by reference function but the code is pass by value function.

Any help would be appreciated.

I stripped away most of the original code in the K&R book to try to better understand it but it is still confusing me.

#define MAXLINE 1000
int getLine(char, int);

int main(){
    char line[MAXLINE];
    int len;

    printf("%s\n", line);         //making sure that there is nothing in line
    len = getline(line, MAXLINE); 
    printf("length: %d\n", len);  
    printf("%s", line);           //now there's something in line!?

    return 0;
}

int getline(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;
}

Solution

  • int getline(char s[], int lim) is equivalent to int getline(char *s, int lim).

    What that means is that s is a pointer, pointing to the location in memory where char line[MAXLINE] is stored, so by modifying the contents of s, you actually modify the line array declared in main.

    Also you have a small bug in the code in the question. I believe that the forward declaration int getLine(char, int); should be int getline(char[], int); (note the [] and the lowercase l);