below is the implementation of library function gets()
// I know gets() can cause buffer overflow easily, just use this fuction for demo purpose
char *gets(char *s)
{
int c;
char *dest = s;
while ((c = getchar()) != ’\n’ && c != EOF)
*dest++ = c;
if (c == EOF && dest == s)
return NULL;
*dest++ = ’\0’;
return s;
}
void echo()
{
char buf[8];
gets(buf);
}
I have two questions:
Q1-for this statement *dest++ = c;
, we know that postfix increment has a higher precedence than dereference, so *dest++
is equivalent to *(dest++)
, but isn't that we lose the first element buf[0]?
Q2-why the gets()
need to return a char pointer? isn't the return pointer the same as the argument s
? isn't it more straightforward to make gets()
method signature as:
void gets(char *s)