Exception thrown at 0x00007FFCCCB30369 (ucrtbased.dll) in Project3.exe: 0xC0000005: Access violation writing location 0x000000894B700000

huangapple go评论80阅读模式
英文:

Exception thrown at 0x00007FFCCCB30369 (ucrtbased.dll) in Project3.exe: 0xC0000005: Access violation writing location 0x000000894B700000

问题

我正在学习C语言,在Microsoft Visual Studio中运行了这些代码,但出现了访问冲突异常。您能帮我找出原因吗?

  1. #include <stdio.h>
  2. int main() {
  3. char name[10];
  4. printf("Enter your name\n");
  5. scanf_s("%s", name);
  6. printf("Welcome %s\n", name);
  7. return 0;
  8. }

我已经查找了很多解决方案,但有些并不起作用。我尝试删除name中的&,但没有帮助。

英文:

I'm studying C language, I ran these codes in Microsoft Visual Studio, but I got an access violation exception, Could you please help me find out the reason?

  1. #include &lt;stdio.h&gt;
  2. int main() {
  3. char name[10];
  4. printf(&quot;Enter your name\n&quot;);
  5. scanf_s(&quot;%s&quot;, name);
  6. printf(&quot;Welcome %s\n&quot;, name);
  7. return 0;
  8. }

I've looked for numerous solutions to this, however some are no effective. I tried removing the &amp; from the name, but that didn't help.

答案1

得分: 2

你也需要将 name 的长度提供给 scanf_s 函数:

  1. scanf_s("%s", name, (unsigned)sizeof name);

没有提供长度的话,程序会出现未定义的行为,可能导致崩溃。

英文:

You need to provide the length of name to scanf_s too:

  1. scanf_s(&quot;%s&quot;, name, (unsigned)sizeof name);

Without the lenght, the program will have undefined behavior and may therefore crash

huangapple
  • 本文由 发表于 2023年2月19日 17:12:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定