【问题标题】:How to compare pointer and integer? [duplicate]如何比较指针和整数? [复制]
【发布时间】:2015-08-29 22:42:01
【问题描述】:

我正在尝试检查指针是否指向某个字符。

像这样:

#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;

}

但我经常收到警告:警告:指针和整数之间的比较 if(*s=="a")

可以比较指针和整数吗?

还有其他方法可以解决这个问题吗?

我可以在不打印的情况下找出指向 *s 的字母吗?

【问题讨论】:

  • 第 1 步:以可读的方式格式化您的代码。

标签: c pointers char


【解决方案1】:

chars 包含在 '' 而不是 ""

#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;

}

【讨论】:

    【解决方案2】:

    "a" 不是字符,它是字符串文字。 'a' 是一个字符文字,这就是您在此处寻找的内容。

    还请注意,在您的比较中,*s == "a" 实际上是 "a" 是指针,*s 是整数...... * 取消引用 s,导致 @987654328 @(整数)存储在s 指向的地址。但是,字符串文字充当指向字符串 "a" 的第一个字符的指针。

    此外,如果您通过将比较更改为*s == 'a' 来修复比较,则您只是检查s第一个字符 是否为'a'。如果您想比较字符串,请参阅strcmp

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      相关资源
      最近更新 更多