objective-c 指针和整数之间的比较('int *' 和 'int')
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18673511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
comparison between pointer and integer ('int *' and 'int')
提问by RGriffiths
I am confused as to why I get this warning:
我很困惑为什么会收到此警告:
I intiate matchObsFlag with:
我用以下命令启动 matchObsFlag:
int *matchObsFlag=0;
but when I run this line:
但是当我运行这条线时:
if (matchObsFlag == 1)
I get this warning. Any ideas?
我收到这个警告。有任何想法吗?
回答by LudoZik
You surely get a warning because you did not cast 1 as such (int*) 1so you test an equality between different things : an address and an int.
您肯定会收到警告,因为您没有像这样转换 1,(int*) 1因此您测试了不同事物之间的相等性:地址和整数。
So it is either if(matchObsFlag == (int*)1)or if(*matchObsFlag == 1)depending on what you wanna do.
因此,要么是if(matchObsFlag == (int*)1)还是 if(*matchObsFlag == 1)取决于你想做些什么。
回答by Mahesh
int *matchObsFlag=0;
The type of matchObsFlagis int*while the constant literal is of type int. Comparison between the unrelated types is causing the warning.
matchObsFlagis的类型,int*而常量文字的类型是int。不相关类型之间的比较导致警告。
matchObsFlagis a NULL pointer. matchObsFlagneeds to point to a valid memory location if you wish to compare the value pointed by the pointer.
matchObsFlag是一个空指针。matchObsFlag如果您希望比较指针指向的值,则需要指向有效的内存位置。
int number = 1;
matchObsFlag = &number;
Now, to compare the value, you need to dereference the pointer. So try -
现在,要比较值,您需要取消引用指针。所以试试——
if (*matchObsFlag == 1)
{
// ...
}

