cpointerschar

How to compare a pointer and an integer


I'm trying to check if a pointer is pointing at some char, like this:

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

But I constantly get a warning:

warning: comparison between pointer and integer if(*s=="a")

Is it possible to compare pointers and integers?

Is there another way to resolve this problem?

Can I find out at which letter is pointing *s without printing it?


Solution

  • "a" is not a character, it is a string literal. 'a' is a character literal, which is what you are looking for here.

    Also note that in your comparison *s == "a" it is actually the "a" which is the pointer, and *s which is the integer... The * dereferences s, which results in the char (an integer) stored at the address pointed to by s. The string literal, however, acts as a pointer to the first character of the string "a".

    Furthermore, if you fix the comparison by changing it to *s == 'a', you are only checking whether the first character of s is 'a'. If you wish to compare strings, see strcmp.