0

the code below works in the following way: it basically reads every single char from the stdin using a function called _getchar, allocates them in an array which finally ends up returning it if c =! EOF.

I'd like to just know what's doing the statement (*lineptr)[n_read] = '\0'; in the code below:

#include <unistd.h>
#include <stdlib.h>

int _getchar(void)
{
    int rd;
    char buff[2];

    rd = read(STDIN_FILENO, buff, 1);

    if (rd == 0)
        return (EOF);
    if (rd == -1)
        exit(99);

    return (*buff);
}

ssize_t _getline(char **lineptr, size_t *n, FILE *stream)
{
    char *temp;
    const size_t n_alloc = 120;
    size_t n_read = 0;
    size_t n_realloc;
    int c;

    if (lineptr == NULL || n == NULL || stream == NULL)
        return (-1);

    if (*lineptr == NULL)
    {
        *lineptr = malloc(n_alloc);
        if (*lineptr == NULL)
            return (-1);
        *n = n_alloc;
    }
    while ((c = _getchar()) != EOF)
    {
        if (n_read >= *n)
        {
            n_realloc = *n + n_alloc;
            temp = realloc(*lineptr, n_realloc + 1);

            if (temp == NULL)
                return (-1);

            *lineptr = temp;
            *n = n_realloc;
        }
        n_read++;
        (*lineptr)[n_read - 1] = (char) c;

        if (c == '\n')
            break;

    }
    if (c == EOF)
        return (-1);
    (*lineptr)[n_read] = '\0';
    return ((ssize_t) n_read);
}
NoahVerner
  • 937
  • 2
  • 9
  • 24

2 Answers2

1

char **lineptr means lineptr contains the adress of a char pointer.

A pointer is a variable that contains an adress. So by writing *lineptryou're getting that adress.

In your case, **lineptr <=> *(*lineptr) <=> (*lineptr)[0]

Edit : btw I was not answering the question... the instruction (*lineptr)[n_read] = '\0' means you're ending your string ('\0' is EOF (End Of Line) character).

tony_merguez
  • 307
  • 2
  • 11
  • No. It means you are assigning zero. `ptr` may hava any type for example `uint64_t **` or `double **`. It does not have to be a string. – 0___________ Dec 01 '21 at 17:49
  • So, does this mean that ```(*lineptr)[n_read] = '\0';``` will null terminate the ```[n_read]``` array at its last position? @0___________ – NoahVerner Dec 01 '21 at 19:32
  • 1
    No, it will place zero at `n_read` char element of the pointer referenced by `lineptr` – 0___________ Dec 01 '21 at 19:55
1

They look the same but are different.

The fist one:

int (*ptr)[something]; 

defines the pointer to int something elements array

The latter

(*ptr1)[something]   //witohut type in front of it.

means derefence pointer ptr1 and then dereference the result of previous dereference with added something.

And it is an equivalent of

*((*ptr1) + something)
0___________
  • 60,014
  • 4
  • 34
  • 74
  • So, does this mean that ```(*lineptr)[n_read] = '\0';``` will null terminate the ```[n_read]``` array at its last position? – NoahVerner Dec 01 '21 at 19:31