warning: comparison between pointer and integer in C

无人久伴 提交于 2019-12-20 04:51:14

问题


I get a warning

warning: comparison between pointer and integer

on the line containing if from the next piece of code:

char cwd[1024];

if (getcwd(cwd, sizeof(cwd)) != (char*)NULL)
    printf("%s\n",cwd);
else
    error_print("error in pwd");

how and what do I need to fix?


回答1:


Do you include unistd.h? If not, the error appears because your C compiler is assuming getcwd returns int.

The fix? Include unistd.h




回答2:


The prototype of getcwd is

char *getcwd(char *buf, size_t size);

Make sure you include <unistd.h> otherwise the return type would default to int.

Here, even Ideone gives its Current Working Directory




回答3:


have you included the .h necessary so that the compiler understands what getcwd returns?

the behavior of your c compilers is probably to assume an int return value from every undefined function.




回答4:


In the return types section of the following link, getcwd returns null on failure. Thus, instead of checking for != (char *)NULL just check for != NULL

http://linux.die.net/man/3/getcwd




回答5:


Modify line with this one if (getcwd(cwd, sizeof(cwd)) != NULL)



来源:https://stackoverflow.com/questions/5654685/warning-comparison-between-pointer-and-integer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!