Search code examples
c++strchr

use of strchr() giving error


I am trying to find the occurrence of characters of one string(s1) in other string(s2).

This is part of my code.

for(;i<strlen(s1);i++)
{
   int x=strchr(s2,s1[i]);
   if(x>0)
   count++;
}

But on compiling I get an error pointing to strchr() and says

error: invalid conversion from ‘char*’ to ‘int’ [-fpermissive]

Anyone explain what is problem in using strchr() function.


Solution

  • Assignment is wrong strchr doesn't returns int but returns address of first char in string found:

    int x=strchr(s2,s1[i]);
    

    should be:

    char* x = strchr(s2, s1[i]); 
    //         ^ returns char* 
    

    Read manual

    char *strchr(const char *s, int c);

    RETURN VALUE
    The strchr() and strrchr() functions return a pointer to the matched character or NULL if the character is not found. The terminating null byte is considered part of the string, so that if c is specified as '\0', these functions return a pointer to the terminator.

    And so:

    if(x>0)
    

    should be:

    if(x != NULL)
    

    or just if(x)