Hello,
so the problem was to create a program that took input from command line to function as a rudimentary calculator: e.g 3 + 2, 5 * 4, 2/3 and so on. We were to take those arguments and pass them and a pointer to a function in to the "calc" function and do the appropriate task and print the result. I attempted casting the functions as int and returning the values, and I have attempted to use pointers for the parameters but I have been unable to get program to work properly. When it's passing values into the calc function I get a segmentation fault. Any ideas what I might be doing wrong? I've never been the strongest coder, and most of my experience is in Java. Any help would be greatly appreciated!
#include <stdio.h>
void calc(void(* f)(int, int), int n1, int n2);
void add(int n1, int n2);
void sub(int n1, int n2);
void mult(int n1, int n2);
void div(int n1, int n2);
int main(int num1, char op, int num2) {
if (strcmp(op, "+") == 0)
calc(add, num1, num2);
else if (strcmp(op, "+") == 0)
calc(sub, num1, num2);
else if (strcmp(op, "+") == 0)
calc(mult, num1, num2);
else if (strcmp(op, "+") == 0)
calc(div, num1, num2);
printf("Nothing done!\n");
return 0;
}
void calc(void(* f)(int, int), int n1, int n2) {
(*f)(n1, n2);
}
void add(int n1, int n2) {
int total = n1 + n2;
printf("%d", total);
}
void sub(int n1, int n2) {
int total = n1 - n2;
printf("%d", total);
}
void mult(int n1, int n2) {
int total = n1 * n2;
printf("%d", total);
}
void div(int n1, int n2) {
int total = n1 / n2;
printf("%d", total);
}
}