5
FILE *fd;
if (fd=fopen(fileName,"r") == NULL)
{   
    printf("File failed to open");
    exit(1);
}

这是一个代码片段。当我用 gcc 编译它时,我收到以下警告:-

warning: assignment makes pointer from integer without a cast

当我将fd=fopen(argv[2],"r")放在括号内时,问题就解决了。

当括号没有放置时,我无法理解我在哪里将整数转换为指针。

4

6 回答 6

14

由于运算符优先规则,条件被解释为fd=(fopen(fileName,"r") == NULL)。结果==是整数,fd是指针,因此是错误消息。

考虑代码的“扩展”版本:

FILE *fd;
int ok;
fd = fopen(fileName, "r");
ok = fd == NULL;
// ...

您是否希望最后一行被解释为(ok = fd) == NULL, 或ok = (fd == NULL)

于 2010-01-22T14:09:05.813 回答
3

相等运算符的优先级高于赋值运算符。只需将您的代码更改为:

FILE *fd;
if ((fd=fopen(fileName,"r")) == NULL)
{   
    printf("File failed to open");
    exit(1);
}
于 2010-01-22T14:08:35.973 回答
2

==优先级高于=,因此它比较fopen()to的结果NULL,然后将其分配给fd

于 2010-01-22T14:09:15.837 回答
1

您需要在作业周围加上括号:

if ((fd=fopen(fileName,"r")) == NULL)
....
于 2010-01-22T14:08:15.853 回答
1

== 的优先级高于 =。

于 2010-01-22T14:09:39.157 回答
-1

您是否进行了以下操作?

#include <stdio.h>

没有这个,编译器假定所有函数都返回一个int.

于 2010-01-22T14:08:10.393 回答