使用旗帜,-pedantic -Wall -ansi,我注意到了
初始化变量f1=fopen(argv[1],"r");
然后传递变量
f1
if
语句中的warning: assignment makes pointer from integer without a cast [enabled by default]
语句没有错误。
然而,当我在if语句中初始化变量时,它会抛出一个警告:
FILE *f1;
FILE *f2;
f1=fopen(argv[1],"r");
if(f1==NULL)
{
fprintf(stderr,"unable to open file - %s\n",f1);
}
if(f2=fopen("output.txt","w")==NULL) /*throws warning*/
{
fprintf(stderr,"unable to open file - %s\n",f2);
}
我有自己的想法,但我不确定为什么会这样。
{{1}}
我已经测试了f1和f2两种方式的初始化,并对两者都得到相同的响应。
答案 0 :(得分:3)
if (f2 = fopen("output.txt","w") == NULL)
相当于:
if (f2 = (fopen("output.txt","w") == NULL))
根据f2
是否等于1
,0
分配fopen("output.txt","w")
或NULL
。
您需要的是:
if ((f2 = fopen("output.txt","w")) == NULL)
答案 1 :(得分:3)
if(f2=fopen("output.txt","w")==NULL)
==
的优先级高于=
,因此您实际上在指针中存储了布尔值(在C90中为int
)。添加一些括号:
if((f2 = fopen("output.txt","w")) == NULL)