4

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;
}
Robur_131
  • 374
  • 5
  • 15
  • 4
    The code passes a pointer by value (using unintuitive syntax), you can then use this pointer to modify the array . The book will explain this at some stage – M.M Aug 23 '19 at 00:13
  • 1
    Arrays decay to pointers when passed to function - a pointer to the first element is passed to the function. – Tony Tannous Aug 23 '19 at 00:21
  • 1
    the most succinct way to put this is to note that the value of a pointer *is* a reference – landru27 Aug 23 '19 at 00:42

1 Answers1

4

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);

N Alex
  • 1,014
  • 2
  • 18
  • 29