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)
The function
strcmphas the following declarationAs you can see the both its parameters have the pointer type
const char *.But in you program in this call of
strcmpyou supplied the first argument
p[i]of the typechar. It seems you want to compare two charactersYou could use the function
strcmpbut you have to supply a string as the first argument of the function something likeThis call of
strcmpis 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
howmanyDashshould have the qualifierconstbecause 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 functionstrchr).The function can be declared and defined the following way.
And in main you can write
With using the function
strchrthe functionhowManyDashcan be written the following way