如何比较指针和整数?
How to compare pointer and integer?
我正在尝试检查指针是否指向某个字符。
像这样:
#include<stdio.h>
#include<string.h>
#define a 3
int func(char *);
int main()
{
char *s="a";
int type;
type=func(s);
printf("%d",type);
return 0;
}
int func(char *s)
{
int type;
if(*s=="a")
{
type=1;
}
return type;
}
但我不断收到警告:警告:指针和整数之间的比较
如果(*s=="a")
是否可以比较指针和整数?
还有其他方法可以解决这个问题吗?
我可以在不打印的情况下找出哪个字母指向 *s 吗?
"a"
不是一个字符,它是一个字符串文字。 'a'
是一个字符字面量,这就是您在这里要查找的内容。
另请注意,在您的比较中 *s == "a"
实际上是 "a"
指针,*s
是整数... *
取消引用s
,这导致 char
(整数)存储在 s
指向的地址处。然而,字符串文字充当指向字符串 "a"
.
的第一个字符的指针
此外,如果您通过将比较更改为 *s == 'a'
来修复比较,您只是在检查 s
的 第一个字符 是否为 'a'
.如果您想比较字符串,请参阅 strcmp
.
char
包含在 ''
而不是 ""
中
#include<stdio.h>
#include<string.h>
#define a 3
int func(char *);
int main()
{
char value = 'a';
char *s=&value;
int type;
type=func(s);
printf("%d",type);
return 0;
}
int func(char *s)
{
int type;
if(*s=='a') //or if(*s==3)
{
type=1;
}
return type;
}
我正在尝试检查指针是否指向某个字符。
像这样:
#include<stdio.h>
#include<string.h>
#define a 3
int func(char *);
int main()
{
char *s="a";
int type;
type=func(s);
printf("%d",type);
return 0;
}
int func(char *s)
{
int type;
if(*s=="a")
{
type=1;
}
return type;
}
但我不断收到警告:警告:指针和整数之间的比较 如果(*s=="a")
是否可以比较指针和整数?
还有其他方法可以解决这个问题吗?
我可以在不打印的情况下找出哪个字母指向 *s 吗?
"a"
不是一个字符,它是一个字符串文字。 'a'
是一个字符字面量,这就是您在这里要查找的内容。
另请注意,在您的比较中 *s == "a"
实际上是 "a"
指针,*s
是整数... *
取消引用s
,这导致 char
(整数)存储在 s
指向的地址处。然而,字符串文字充当指向字符串 "a"
.
此外,如果您通过将比较更改为 *s == 'a'
来修复比较,您只是在检查 s
的 第一个字符 是否为 'a'
.如果您想比较字符串,请参阅 strcmp
.
char
包含在 ''
而不是 ""
#include<stdio.h>
#include<string.h>
#define a 3
int func(char *);
int main()
{
char value = 'a';
char *s=&value;
int type;
type=func(s);
printf("%d",type);
return 0;
}
int func(char *s)
{
int type;
if(*s=='a') //or if(*s==3)
{
type=1;
}
return type;
}