I'm trying to build a simple calculator that would perform multiplication and addition.
I have this code
#include <stdio.h>
#include <string.h>
long result = 0;
long *resultPointer = &result;
long plus(long *current, long num) {
return (*current + num);
}
long krat(long *current, long num) {
return (*current * num);
}
int main() {
char operator[4];
long num;
printf("%d\n", 0);
while(scanf("%s %li", &operator[0], &num) != EOF){
if (num > 0) {
if (strcmp(operator, "krat") == 0) {
*resultPointer = krat(&result, num);
}
if (strcmp(operator, "plus") == 0) {
*resultPointer = plus(&result, num);
}
printf("%li\n", result);
}
}
return 0;
}
this is the input for the program
plus 123456789
krat 123456789
plus 0
krat 2
krat 3
krat 4
krat 5
krat 6
and this is the output
0
123456789
15241578750190521
30483157500381042
91449472501143126
365797890004572504
1828989450022862520
-7472807373572376496
The problem is that when the numbers get bigger and bigger they turn to negative. Is this the problem with memory allocation for the variables and how to address this?