Search code examples
cif-statementcharinitializationstrcmp

How to fix expected 'const char *' but argument is of type 'char **` while using strcmp() in a function


It's supposed to be a function that finds the sum, difference etc of a two numbers depending on the chosen operator but when I use strcmp() to check the chosen operator I get the error expected 'const char *' but argument is of type 'char **'

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include <string.h>

int calc(int ran1,int ran2,char op){
    if(strcmp(op, "+")==0){
        return ran1+ran2;
    }
    if(strcmp(op, "-")==0){
        return ran1-ran2;
    if(strcmp(op, "*")==0){
        return ran1*ran2;
    }
    if(strcmp(op, "/")==0){
        return ran1/ran2;
    }
    }
}
int main(){
    int ran1=25;
    int ran2=5;
    char op="+";
    printf("%d", calc(ran1, ran2, op));

}

Solution

  • It seems that this error message

    expected 'const char *' but argument is of type 'char **'

    does not correspond to the presented code because neither expression of the type char ** is used in the program.

    Also there is a logical error in the function due to the invalid placement of braces

    int calc(int ran1,int ran2,char op){
        if(strcmp(op, "+")==0){
            return ran1+ran2;
        }
    
        if(strcmp(op, "-")==0){
            return ran1-ran2;
            if(strcmp(op, "*")==0){
                return ran1*ran2;
            }
            if(strcmp(op, "/")==0){
                return ran1/ran2;
            }
        }
    }
    

    Nevertheless for starters this initialization

    char op="+";
    

    is incorrect. It seems you mean

    char op = '+';
    

    That is you need to initialize the object op of the type char with the integer character constant '+' instead of the string literal "+".

    As the parameter op has the type char

    int calc(int ran1,int ran2,char op){
    

    then it may not be used in a call of strcmp like

     if(strcmp(op, "+")==0){
    

    It is enough to use just the equality operator == in this and other similar if statements like

    if ( op == '+' )
    

    Take into account that instead of the if statements you could use a switch statement. For example

    switch ( op )
    {
    case '+':
        //...
    case '-':
        //...
    }