简体   繁体   English

c scanf_s中的异常

[英]Exception in c scanf_s

I am trying to write a simple code to input values of an int and a char. 我试图编写一个简单的代码来输入int和char的值。 Visual studio is throwing an exception Visual Studio引发异常

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

    int i;
    char c;

    printf(" Enter the values");
    scanf_s("%c %d",&c,&i);

    return 0;
}

As i run the program and input values, visual studio is throwing an exception saying : Exception thrown at 0x599C939E (ucrtbased.dll) in main.exe: 0xC0000005: Access violation writing location 0x0032133E 当我运行程序并输入值时,Visual Studio抛出一个异常,说:main.exe中的0x599C939E(ucrtbased.dll)抛出异常:0xC0000005:访问冲突写入位置0x0032133E

You need to specify the sizeof memory you want to allocate for your char. 您需要指定要为char分配的内存大小。

 scanf_s("%c %d",&c,1,&i);

Won't return any errors. 不会返回任何错误。 Since the scanf() function is kind of "unsafe", VS forces you to use the scanf_s function, which is a safer option. 由于scanf()函数有点“不安全”,因此VS会强制您使用scanf_s函数,这是一个更安全的选择。 This way, the user won't be able to trick the input. 这样,用户将无法欺骗输入。

For format specifiers as c and s there is required to specify the size of the buffer after the corresponding pointer in the list of arguments. 对于c and s格式说明符,需要在参数列表中的相应指针之后指定缓冲区的大小。

In your case the function call will look like 在您的情况下,函数调用看起来像

scanf_s("%c %d",&c, 1, &i);

For format specifier s the size of the buffer also have to take into account the terminating zero. 对于格式说明s的缓冲区的大小也必须考虑到终止零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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