指针和整数之间的警告比较
Warning comparison between pointer and integer
当我遍历字符指针并检查指针何时到达空终止符时,我收到警告。
const char* message = "hi";
//I then loop through the message and I get an error in the below if statement.
if (*message == "[=10=]") {
...//do something
}
我得到的错误是:
warning: comparison between pointer and integer
('int' and 'char *')
我认为 message
前面的 *
取消引用消息,所以我得到消息指向哪里的值?顺便说一句,我不想使用库函数strcmp
。
应该是
if (*message == '[=10=]')
在 C 中,单引号分隔单个字符,而双引号用于字符串。
这:"[=10=]"
是一个字符串,不是一个字符。字符使用单引号,如 '[=11=]'
.
在这一行...
if (*message == "[=10=]") {
...正如您在警告中看到的...
warning: comparison between pointer and integer
('int' and 'char *')
...您实际上是在将 int
与 char *
进行比较,或者更具体地说,将 int
的地址与 char
.[=20 进行比较=]
要解决此问题,请使用以下方法之一:
if(*message == '[=11=]') ...
if(message[0] == '[=11=]') ...
if(!*message) ...
附带说明一下,如果您想比较字符串,您应该使用 strcmp
或 strncmp
,在 string.h
.
中找到
当我遍历字符指针并检查指针何时到达空终止符时,我收到警告。
const char* message = "hi";
//I then loop through the message and I get an error in the below if statement.
if (*message == "[=10=]") {
...//do something
}
我得到的错误是:
warning: comparison between pointer and integer
('int' and 'char *')
我认为 message
前面的 *
取消引用消息,所以我得到消息指向哪里的值?顺便说一句,我不想使用库函数strcmp
。
应该是
if (*message == '[=10=]')
在 C 中,单引号分隔单个字符,而双引号用于字符串。
这:"[=10=]"
是一个字符串,不是一个字符。字符使用单引号,如 '[=11=]'
.
在这一行...
if (*message == "[=10=]") {
...正如您在警告中看到的...
warning: comparison between pointer and integer ('int' and 'char *')
...您实际上是在将 int
与 char *
进行比较,或者更具体地说,将 int
的地址与 char
.[=20 进行比较=]
要解决此问题,请使用以下方法之一:
if(*message == '[=11=]') ...
if(message[0] == '[=11=]') ...
if(!*message) ...
附带说明一下,如果您想比较字符串,您应该使用 strcmp
或 strncmp
,在 string.h
.