变量'input'周围的堆栈已损坏

Wai*_*hin 1 c

我刚刚开始使用C语言,我遇到了这个错误.我尝试在线查找,但其他线程包含我不熟悉的ARRAY.

#include<stdio.h>
int main(void){

    char input;
    printf("ASCII testing\n");
    scanf( "%d", &input); //the error occurs here but would like to know the solution

    printf("answer is : %c\n" , input);

    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

"运行时检查失败#2 - 变量'输入'周围的堆栈已损坏."

简单的指出将非常感激

//编辑

好吧,我想输入值"66",结果将是B. scanf("%c,&input)接受键盘上的1次击键,这不是我想要的.但是,不过,谢谢你的回复

Eri*_* J. 6

问题

%d 是整数输入的格式说明符,使编译器假定&输入指向整数而不是字符.

scanf( "%d", &input);
Run Code Online (Sandbox Code Playgroud)

应该

scanf( "%c", &input);
Run Code Online (Sandbox Code Playgroud)

为什么这会破坏堆栈

堆栈损坏的原因是输入在堆栈上分配,而scanf假定它占用4个字节(在32位平台上)而不是堆栈上实际分配的1个字节.因此,堆栈上的其他内容(其他变量,返回地址......)将被覆盖.