简体   繁体   中英

Access violation error C

I am a beginner and I am learning C and C++. I am trying to run this code in Visual Studio 2012 Express for Windows Desktop. This is a simple calculator code which I have written by myself! But whenever I run it I get this error Unhandled exception at 0x519600B4 (msvcr110d.dll) in Calculator.exe: 0xC0000005: Access violation writing location 0x00000000.

Forgive me for any mistakes (it is my first time). Thank you!

#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();
}

When using scanf_s , for the %c format string you must specify how many characters you wish to read:

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

The documentation describes the requirement:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM