What does (char *)0 mean in c?

前端 未结 6 2072
臣服心动
臣服心动 2020-12-19 17:47
if ( fgets( line, sizeof(line), stdin ) == (char*) 0 )...

I don\'t understand what this line does,anyone knows?

相关标签:
6条回答
  • 2020-12-19 18:26

    That's a rather odd way of writing a test for the return of a null pointer which indicates an error in fgets().

    I'd write it like this:

    if (!fgets(line, sizeof(line), stdin))
    
    0 讨论(0)
  • 2020-12-19 18:42

    (char*)0 creates the "null" pointer. So you are seeing if the value of fgets is null.

    The documentation for fgets states that it returns null when there is an error or you have reached end of file.

    The full statement appears to be checking if you are at the end of the file, and if so breaking out (though that's a guess).

    0 讨论(0)
  • 2020-12-19 18:44

    It is simply checking the results of fgets for null character pointer.

    According to cplusplus.com

    Return Value

    On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.

    If an error occurs, a null pointer is returned.

    Use either ferror or feof to check whether an error happened or the End-of-File was reached.

    0 讨论(0)
  • 2020-12-19 18:48

    It means a null pointer to char. It would be the same if you replace the (char*)0 with NULL. In this particular case it is checking if there is nothing more to read from the stdin. I think is just a way to be cryptic and showing some spectacular and beautiful features. If you replace it with a NULL you gain in readability without changing the semantic.

    0 讨论(0)
  • 2020-12-19 18:49

    The line checks if fgets return 0. The cast to char* is only to match the return type of fgets:

    char * fgets ( char * str, int num, FILE * stream );
    

    But 0 is implicit converted to char* if you remove it.

    If you need more information on fgets look here

    0 讨论(0)
  • 2020-12-19 18:50
    (char*) 0
    

    Is not a null character, but a pointer to a character at address 0.

    A character containing the value 0 would be:

    (char) 0
    
    0 讨论(0)
提交回复
热议问题