scanf 和 scanf_s 的区别 [英] Difference between scanf and scanf_s

查看:30
本文介绍了scanf 和 scanf_s 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scanfscanf_s 有什么区别?在大学里,我一直在教我使用 scanf,但在我的个人计算机上,Visual Studio 不断发送此警告.

What is the difference between scanf and scanf_s? In the university I have been taught and I am using scanf, but at my personal computer Visual Studio keeps sending this warning.

 error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead.

而且我必须将所有 scanf 更改为 scanf_s 否则程序将无法构建.(我使用的是 Visual Studio 2013)

And I have to change all scanf to scanf_s or the program won't build. (I am using Visual Studio 2013)

推荐答案

是一个专门属于微软编译器的函数.

It is a function that belongs specifically to the Microsoft compiler.

scanf 最初只是读取您键入的任何控制台输入并将其分配给一种变量.

scanf originally just reads whatever console input you type and assign it to a type of variable.

如果您有一个名为 first_name[5] 的数组,并且您将 scanf 用于Alex",则没有问题.如果您有相同的数组并分配Alexander",您可以看到它超过了数组包含的 5 个插槽,因此 C 仍会将其写入不属于该数组的内存中,并且它可能会或可能不会使程序崩溃,取决于是否有东西试图访问和写入不属于 first_name 的内存插槽.这就是 scanf_s 的用武之地.

If you have an array called first_name[5] and you use scanf for "Alex", there is no problem. If you have the same array and assign "Alexander", you can see it exceeds the 5 slots that the array contains, so C will still write it on memory that doesn't belong to the array and it might or might not crash the program, depending if something tries to access and write on that memory slot that doesn't belongs to first_name. This is where scanf_s comes in.

scanf_s 有一个参数(参数),您可以在其中指定缓冲区大小并实际控制输入的限制,这样您就不会使整个建筑物崩溃.

scanf_s has an argument(parameter) where you can specify the buffer size and actually control the limit of the input so you don't crash the whole building.

这篇关于scanf 和 scanf_s 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆