yazze yazze - 3 months ago 7
C Question

Trying to do simple do_operation function in C

I'm going a bit crazy trying to a very simple operation function in C as a beginner, but it seems everything I try failed, although it's supposed to work.

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int calcul(int nb1, int nb2, char *av)
{
int nb = 0;
if (av[2] == '*')
nb = nb1 * nb2;
if (av[2] == '%')
nb = nb1 % nb2;
if (av[2] == '/')
nb = nb1 / nb2;
if (av[2] == '+')
nb = nb1 + nb2;
if (av[2] == '-')
nb = nb1 - nb2;
return (nb);
}

int atoi();

int main(int ac, char **av)
{
printf("%s", av[2]);
if (ac == 4)
printf("%d", calcul(atoi(av[1]), atoi(av[3]), av[2]));
return (0);
}


It seems like at soon as the second argument, which is the operator, goes through the
calcul
function, it change the actual character into either it's ASCII value or something else, thus not being detected properly in the condition.

I've tried to fiddle many ways and look up other snippet, but this is exactly what they were doing and how it's supposed to work (even if I remove the
printf
), so what am I doing wrong?

EDIT Sorry I purposely change the number of argument to get a segfault for something else, here's the "correct" function I'm testing for which I'm getting the problem.

Also the way I'm using this function is by running a simple compiled prog under this format in shell:

./a.out 2 * 3


SOLVED As @Mike pointed out when entering the calculate function, av[2] which is the operator was now considered the first and only character argument, therefor was to be identified with av[0]. Which is a little confusing/tricky.

Answer

You have your indexing wrong. I changed the code a bit assuming that you wanted to print the operator character to make sure it was working.

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int     calcul(int nb1, int nb2, char *av)
{
        int nb = 0;
        printf("%c\n", av[0]);
        if (av[0] == '*')
                nb = nb1 * nb2;
        if (av[0] == '%')
                nb = nb1 % nb2;
        if (av[0] == '/')
                nb = nb1 / nb2;
        if (av[0] == '+')
                nb = nb1 + nb2;
        if (av[0] == '-')
                nb = nb1 - nb2;
        return (nb);
}

int     main(int ac, char **av)
{
        printf("%s\n", av[2]);
        if (ac == 4)
                printf("%d\n", calcul(atoi(av[1]), atoi(av[3]), av[2]));
        return (0);
}

Notice in your 'calcul' funciton you were calling 'av[2]' which is the trying to get the third index of a string containing just your operator character which is NULL.

ETA:

Also a note on the '*' operator. To get it to work you need to call it with an escape character '\'.

ETA2:

Changed the code to match the edits in the answer so it can be called with:

./a 3 + 4
./a 3 '*' 9