c - 访问冲突错误 C

标签 c

我是初学者,正在学习 C 和 C++。我正在尝试在 Visual Studio 2012 Express for Windows Desktop 中运行此代码。这是我自己写的一个简单的计算器代码!但是每当我运行它时,我都会在 Calculator.exe 中收到此错误 Unhandled exception at 0x519600B4 (msvcr110d.dll): 0xC0000005: Access violation writing location 0x00000000.

如有错误请见谅(我是第一次)。谢谢!

#include<stdio.h>
#include<conio.h>

main ()
{
    int num1, num2, result;
    char oper;
    scanf_s("%d%c%d", &num1, &oper, &num2);
    switch(oper)
    {
    case '+':
        result = num1 + num2;
        printf("%d", result);
        break;
    case '-':
        result = num1 - num2;
        printf("%d", result);
        break;
    case '*':
        result = num1 * num2;
        printf("%d", result);
        break;
    case '/':
        result = num1 / num2;
        printf("%d", result);
        break;
    default:
        printf("ERROR: INVALID OR UNRECOGNISED INPUT\n");
        break;
    }
    _getch();
}

最佳答案

使用 scanf_s 时,对于 %c 格式字符串,您必须指定要读取的字符数:

scanf_s("%d%c%d", &num1, &oper, 1, &num2);

documentation描述要求:

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.

关于c - 访问冲突错误 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17082604/

相关文章:

c - 如何 - 使用文件锁求矩阵元素之和 (unix - C/C++)

c++ - 函数指针在C和C++中都立即返回吗?

c - 十六进制 sha1 输出错误

c - 将从第一个到最后一个的数字打印为文本,而不使用 C 中的数组、递归或二进制运算

c - 如何制作具有特殊 header 结构的原始数据包并通过原始 unix 套接字发送

c# - C# 中的 C 样式 union

c - 在 C 中使用具有相同标志的 fopen 打开文件

无法在 C 中打印 "* "

c - mpi.h : Using a type w/o defining it?

c - typedef 指针的大小