PREV INDEX NEXT

Author: Stan Eisenstat
Subject: Re: [Cs223] Why does getline take in a char **lineptr?
Date: Thursday, 20 Feb 2020, 14:05:54


    > The man page for getline says that it takes in char **lineptr as the first
    > argument. How come it isn't char *lineptr instead? ...

getline() needs to return three values:

1) The number of characters read.

2) The address of the buffer containing those
   characters.  Note that this buffer must be
   dynamic (since the length of the line is not
   known in advance) and persistent (that is,
   allocated in the heap segment).

3) The length of that buffer (which may differ
   from the number of characters read).

Only one of these values can be returned as the value of
the function; the other two must be stored in variables
in the calling program, which is done by passing their
addresses as arguments and dereferencing them.

Since the authors of getline() chose to return the
number of characters read, the address of the variable
that will contain the address of the buffer must be an
argument.  The type of that argument must be char** (=
pointer to char*), not char* (= pointer to char).
=====

    >                                                ... I was under the
    > impression that something like char **lineptr is a pointer to a pointer
    > and basically like an array of strings.  The first pointer is how the
    > "array" is stored and the second pointer points to the sequences of chars
    > that make up the string.  getline reads in a single string, not an array,
    > so I am confused to as why it needs a **lineptr.

See above.  The buffer must be a char*, but you need to
pass its address if you want to set it from within
getline().
=====

    > Also is this the reason why we need to pass in the address of a char
    > pointer as an argument as shown in the spec?
    >
    >      size_t n = 0;  char *line = NULL;
    >      while (getline (&line, &n, stdin) != -1) {
    >
    > If getline takes in a single char pointer, we could just pass in
    > 'line' without needing to take the addess of line like '&line',
    > correct?

But then you would not be able to increase the size of
the buffer if necessary to fit the entire line.

--Stan-
PREV INDEX NEXT