Search code examples
ccharc-stringsfunction-definitionstrchr

Getting incompatible integer to pointer conversion error in program. Unsure how/why exactly this is occurring but looking for an explanation


I'm trying to count how many dashes "-" there are in char p[]. I loop over the string, and use the strcmp function to compare what is at the p[i] location to "-". The strcmp function returns 0 if the they are the same.

int howmanyDash( char p[] ){
    int length = strlen(p);
    int i, count = 0;

    for (i = 0; i < length; i++)
    {
        if (strcmp(p[i], "-") == 0)
        {
            ++count;
        }   
    }

    return count;
    
}
int main(){
    char word[20];
    scanf("%s", word);
    int dashCount = howManyDash(word);
    printf("Dashes: %d\n", dashCount);

    return 0;
}

The error I am getting reads as follows: warning: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Wint-conversion] if (strcmp(p[i], "-") == 0)

This warning was generated on line 7: if (strcmp(p[i], "-") == 0)


Solution

  • The function strcmp has the following declaration

    int strcmp(const char *s1, const char *s2);
    

    As you can see the both its parameters have the pointer type const char *.

    But in you program in this call of strcmp

    if (strcmp(p[i], "-") == 0)
    

    you supplied the first argument p[i] of the type char. It seems you want to compare two characters

    if ( p[i] == '-' )
    

    You could use the function strcmp but you have to supply a string as the first argument of the function something like

    if ( strcmp( &p[i], "-" ) == 0 )
    

    This call of strcmp is semantically correct but the condition will evaluate to true only in one case when the string pointed to by the pointer expression &p[i] also represents the string literal "-". In other cases the if statement will evaluates to false.

    Pay attention to that the parameter of the function howmanyDash should have the qualifier const because the passed string is not changed within the function. And there is not necessary to use any standard C string function (though you could use the standard function strchr).

    The function can be declared and defined the following way.

    size_t howmanyDash( const char s[] )
    {
        size_t count = 0;
    
        for ( ; *s; ++s )
        {
            if ( *s == '-' )
            {
                ++count;
            }   
        }
    
        return count;
    }
    

    And in main you can write

    size_t dashCount = howManyDash(word);
    printf("Dashes: %zu\n", dashCount);
    

    With using the function strchr the function howManyDash can be written the following way

    size_t howmanyDash( const char s[] )
    {
        size_t count = 0;
        const char c = '-';
    
        for ( ; ( s = strchr( s, c ) ) != NULL; ++s )
        {
            ++count;
        }
    
        return count;
    }