Search code examples
cgets

How to check what value is being returned by gets() function in C?


I'm trying to print what the gets() fuctions returns in C.

I tried various format specifiers but none seemed to help.

char a[100];
char (*p)[100];
p=gets(a);
printf("%s",p);

it just says segmentation fault.


Solution

  • The gets() function

    The gets function returns [the original argument] if successful. If end-of-file is encountered and no characters have been read into the array, [...] a null pointer is returned. If a read error occurs during the operation, [...] a null pointer is returned.

    So, the gets() function (with C99 or earlier) returns its argument or NULL.

    Note that it was marked obsolescent in C99 (2007 TC) and removed from the Standard in C11.


    char a[100];
    char *p;
    p = gets(a); // assign a (&a[0]) to p if no errors
    printf("%c is the same as %c\n", a[0], p[0]);