我是 C 语言新手,我遇到了这个问题,但不明白为什么会发生这种情况。运行以下代码后,出现一条错误消息: “运行时检查失败 #2 - 变量“op”周围的堆栈已损坏”。
仅供引用,程序应该要求用户提供 2 个整数和一个数学运算符,然后对这两个数字执行运算(例如 5,3,+ --> 5+3=8)。除了最后弹出的错误消息之外,它工作得很好。 我只想了解为什么会出现此消息,无需给我有关我的编码风格等的注释 - 这对我来说仍然是新的...... 谢谢
#include <stdio.h>
#include <stdlib.h>
void askUser();
double calculateImpl(int *, char *);
typedef struct _myStruct
{
double result;
double(*calculate) (int *, char *);
} myStruct;
int main(void) {
puts("Hello World!");
askUser();
return EXIT_SUCCESS;
}
void askUser(){
int numbers[2] = { 0, 0 };
char op[1] = { '.' };
printf("Please choose 2 integers:\n");
printf("1st integer: ");
scanf("%d", &numbers[0]);
printf("\n2nd integer: ");
scanf("%d", &numbers[1]);
printf("\nchoose a mathematical operator\n(+,-,*,/; can't choose / if the second number is 0: ");
scanf("%s", &op[0]);
while (numbers[1] == 0 && op[0] == '/'){
printf("\ncan't choose / while the second number is 0.\nchoose a different operation: ");
scanf("%s", &op[0]);
}
printf("the result of %d %s %d is ", numbers[0], &op[0], numbers[1]);
myStruct strct;
strct.calculate = calculateImpl;
strct.result = strct.calculate(numbers, op);
printf("%lf\n", strct.result);
}
double calculateImpl(int * numbers, char * op){
double result = 0;
switch (op[0])
{
case '+':
result = numbers[0] + numbers[1];
break;
case '-':
result = numbers[0] - numbers[1];
break;
case '*':
result = numbers[0] * numbers[1];
break;
case '/':
result = numbers[0] / numbers[1];
break;
default:
break;
}
return result;
}
最佳答案
scanf("%s", &op[0]);
^ use %c
使用%c
说明符在字符变量中获取输入。您将 wring 参数传递给 %s
说明符。
在 while
循环中还有 scanf
,也请使用正确的说明符。
将 op
声明为 char
-
char op; // you don't need char op[1]
像这样写-
scanf(" %c", &op); // at both places
并在循环此行之后 -
printf("the result of %d %s %d is ", numbers[0], &op[0], numbers[1]);
要打印char
,请不要传递其地址并使用%c
-
printf("the result of %d %c %d is ", numbers[0], op, numbers[1]);
然后传递你的函数 char
而不是 char *
-
double calculateImpl(int *, char );
并在您的程序中进行相应的更改。
关于c - "Run-Time Check Failure #2 - Stack around the variable ' op ' was corrupted"错误(C语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33328108/