为什么我的小程序崩溃?
问题描述:
我试图做一个小例程,你输入例如1 + 2和输出应该是这两个数字的总和。但它不断崩溃,或者不会做任何事情。这是怎么回事?为什么我的小程序崩溃?
#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;
}
答
atoi
采用参数作为const char *
而不是char
。您的变量类型为char
,其中atoi
将字符串转换为int
类型。
同样,您通过char *
作为%d
的参数scanf
,导致未定义的行为。
scanf(" %d%d%d", &first, &op, &second)
^^^^^^ expects int * not char *
发布完整的编译输出。阅读:http://www.cplusplus.com/reference/cstdio/scanf/和一些关于C – Inline
的好书,修正如[this](http://ideone.com/RKj9B1) – BLUEPIXY