简体   繁体   English

(char *)0在c中的含义是什么?

[英]What does (char *)0 mean in c?

if ( fgets( line, sizeof(line), stdin ) == (char*) 0 )...

我不明白这条线的作用,谁知道呢?

That's a rather odd way of writing a test for the return of a null pointer which indicates an error in fgets() . 这是一种编写测试的奇怪方法,用于返回空指针,指示fgets()的错误。

I'd write it like this: 我写的是这样的:

if (!fgets(line, sizeof(line), stdin))
(char*) 0

Is not a null character, but a pointer to a character at address 0. 不是空字符,而是指向地址0处字符的指针。

A character containing the value 0 would be: 包含值0的字符将是:

(char) 0

It means a null pointer to char. 它表示指向char的空指针。 It would be the same if you replace the (char*)0 with NULL. 如果用NULL替换(char *)0,它将是相同的。 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. 如果用NULL替换它,则可以在不改变语义的情况下获得可读性。

The line checks if fgets return 0. The cast to char* is only to match the return type of fgets : 该行检查fgets返回0.转换为char*只是为了匹配fgets的返回类型:

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

But 0 is implicit converted to char* if you remove it. 但如果删除0,则隐式转换为char*

If you need more information on fgets look here 如果您需要有关fgets更多信息,请查看此处

(char*)0 creates the "null" pointer. (char *)0创建“null”指针。 So you are seeing if the value of fgets is null. 所以你看到fgets的值是否为null。

The documentation for fgets states that it returns null when there is an error or you have reached end of file. fgets的文档声明当出现错误或者您已到达文件末尾时它返回null。

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). 完整的陈述似乎是在检查你是否在文件的末尾,如果是这样的话(尽管这是猜测)。

It is simply checking the results of fgets for null character pointer. 它只是检查空字符指针的fgets结果。

According to cplusplus.com 根据cplusplus.com

Return Value 回报价值

On success, the function returns the same str parameter. 成功时,该函数返回相同的str参数。 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. 如果遇到文件结尾且未读取任何字符,则str的内容保持不变,并返回空指针。

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. 使用ferror或feof检查是否发生错误或是否已达到文件结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM