c - Code crashes after call to scanf -


i'm programming beginner , need code. it's supposed calculator 6 functions including main. 4 operations , 1 take input 2 numbers. crashes enter second input number. also, had problem returning values function input() main function perform operations. maybe has scanning opt?

#include <stdio.h>  int add(int n1, int n2); int subtract(int n1, int n2); int multiply(int n1, int n2); int divide(int n1, int n2); void input(int *n1, int *n2);   int main(void) {     int n1, n2, ret;     char opt;       input(&n1, &n2);      printf("addition -> 1\nsubtraction -> 2\nmultiplication -> 3\ndivision -> 4\nreset -> r\nexit -> e\n");      scanf("%c", &opt);        switch(opt){             case '1':                  ret = add(n1, n2);                 printf("the sum %d\n", ret);                 break;             case '2':                 ret = subtract(n1, n2);                 printf("the difference %d\n", ret);                 break;             case '3':                  ret = multiply(n1, n2);                 printf("the sum %d\n", ret);                  break;                           case '4':                  ret = divide(n1, n2);                 printf("the sum %d\n", ret);                 break;     }      return 0;     }   void input(int *n1, int *n2) {     int a, b;         printf("enter first number: \n");     scanf("%d", &n1);      printf("enter second number: \n");     scanf("%d", &n2);         *n1 = a;     *n2 = b; }  add(n1, n2) {     int result;     result = (n1+n2);     return result; }  subtract(n1, n2) {     int result;     result = (n1-n2);     return result; }  divide(n1, n2) {     int result;     result = (n1/n2);     return result; }  multiply(n1, n2) {     int result;     result = (n1*n2);     return result; } 

am doing right?

the problem in input:

printf("enter first number: \n"); scanf("%d", &n1);  printf("enter second number: \n"); scanf("%d", &n2);    

the %d format specifier expects int * argument. since n1 , n2 int *, means &n1 , &n2 of type int **. causes segmentation fault.

to fix this, pass in n1 , n2:

void input(int *n1, int *n2) {     printf("enter first number: \n");     scanf("%d", n1);      printf("enter second number: \n");     scanf("%d", n2);         getchar(); } 

you'll notice a , b not required if this. note call getchar() consume newline in input buffer. if don't that, newline picked scanf in main , switch statement won't entered.

also, 4 math functions don't specify return type. since prototypes these function declare them returning int, , because int default return type function, manages work. however, should specify return type.


Comments