C语言 指针和整数的警告比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32510218/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:07:11  来源:igfitidea点击:

Warning comparison between pointer and integer

cnull-terminated

提问by catee

I am getting a warning when I iterate through the character pointer and check when the pointer reaches the null terminator.

当我遍历字符指针并检查指针何时到达空终止符时,我收到一条警告。

 const char* message = "hi";

 //I then loop through the message and I get an error in the below if statement.

 if (*message == "
warning: comparison between pointer and integer
      ('int' and 'char *')
") { ...//do something }

The error I am getting is:

我得到的错误是:

if (*message == '
if (*message == "
warning: comparison between pointer and integer
      ('int' and 'char *')
") {
')

I thought that the *in front of messagedereferences message, so I get the value of where message points to? I do not want to use the library function strcmpby the way.

我认为*前面的message取消引用消息,所以我得到消息指向的值?strcmp顺便说一下,我不想使用库函数。

回答by blakelead

It should be

它应该是

if(*message == '##代码##') ...
if(message[0] == '##代码##') ...
if(!*message) ...

In C, simple quotes delimit a single character whereas double quotes are for strings.

在 C 中,单引号用于分隔单个字符,而双引号用于字符串。

回答by dbush

This: "\0"is a string, not a character. A character uses single quotes, like '\0'.

this:"\0"是一个字符串,而不是一个字符。字符使用单引号,例如'\0'.

回答by Fiddling Bits

In this line ...

在这一行...

##代码##

... as you can see in the warning ...

......正如你在警告中看到的......

##代码##

... you are actually comparing an intwith a char *, or more specifically, an intwith an address to a char.

...您实际上是将 anint与 a进行比较char *,或者更具体地说,将 anint与一个地址进行比较char

To fix this, use one of the following:

要解决此问题,请使用以下方法之一:

##代码##

On a side note, if you'd like to compare strings you should use strcmpor strncmp, found in string.h.

附带说明一下,如果您想比较字符串,您应该使用strcmpstrncmp,在string.h.