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);
}
CodePudding user response:
char **lineptr
means lineptr
contains the adress of a char
pointer.
A pointer is a variable that contains an adress. So by writing *lineptr
you'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).
CodePudding user response:
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)