Search code examples
ccharatoi

Why is my small program crashing?


I'm trying to make a tiny program where you input for example 1 + 2 and the output should be the sum of those two numbers. But it keeps crashing and or won't do anything. What's going on?

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

int main(){

char *op;
char *first;
char *second;

printf("Enter operation\n");
scanf(" %s%s%s", &first, &op, &second);

int num1;
int num2;
int num3;
int add;

num1 = atoi(first);
num2 = atoi(op);
num3 = atoi(second);

add = num1 + num3;


printf("Sum = %i\n",add);

return 0;
}

Solution

  • atoi takes argument as const char * and not char . Your variables are of type char where as atoi converts string to int type.

    Also you pass char * as argument to %d in scanf , that results in undefined behavour.

    scanf(" %d%d%d", &first, &op, &second)
            ^^^^^^ expects int * not char *