英文:
Exception thrown at 0x00007FFCCCB30369 (ucrtbased.dll) in Project3.exe: 0xC0000005: Access violation writing location 0x000000894B700000
问题
我正在学习C语言,在Microsoft Visual Studio中运行了这些代码,但出现了访问冲突异常。您能帮我找出原因吗?
#include <stdio.h>
int main() {
char name[10];
printf("Enter your name\n");
scanf_s("%s", name);
printf("Welcome %s\n", name);
return 0;
}
我已经查找了很多解决方案,但有些并不起作用。我尝试删除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?
#include <stdio.h>
int main() {
char name[10];
printf("Enter your name\n");
scanf_s("%s", name);
printf("Welcome %s\n", name);
return 0;
}
I've looked for numerous solutions to this, however some are no effective. I tried removing the &
from the name
, but that didn't help.
答案1
得分: 2
你也需要将 name
的长度提供给 scanf_s
函数:
scanf_s("%s", name, (unsigned)sizeof name);
没有提供长度的话,程序会出现未定义的行为,可能导致崩溃。
英文:
You need to provide the length of name
to scanf_s
too:
scanf_s("%s", name, (unsigned)sizeof name);
Without the lenght, the program will have undefined behavior and may therefore crash
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论