运行 我的代码时出现运行时错误
Runtime error when running my code
当我编译 C 代码时,有时会收到此错误消息。
Mycode.exe has stopped working..
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution available.
我的 C 代码:
#include<stdio.h>
main(){
char a;
a="S";
printf("%s",a);
}
那么出现这个问题的原因是什么?
语法错误、运行时错误或其他原因?
将您的代码更改为
#include<stdio.h>
int main()
{
char a;
a='S';
printf("%c",a);
return 0;
}
它会正常工作。
当您使用 %s
调用 printf 时,这意味着 printf
将在给定地址开始打印并在到达空终止符时结束,因为您给 printf 一个 char
而不是 pointer
到 char
,它会尝试使用 a
中写入的值开始打印。
a
是一个占用一个字节的 space 的字符,而在 64 位系统中地址是 8 个字节,所以基本上 printf 取 'a' 中的值和接下来的 7 个字节(随机的 'garbage')并尝试将其用作停止打印的地址。
这就是为什么它有时会像您所说的那样工作,有时这些随机地址可以从中开始打印,但有时它们是您无权访问的地址,例如 OS 使用的内存区域或内核。
要解决这个问题,您需要使 a
成为 char *
而 而不是 成为 char
,并为其分配一个字符串。
当我编译 C 代码时,有时会收到此错误消息。
Mycode.exe has stopped working..
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution available.
我的 C 代码:
#include<stdio.h>
main(){
char a;
a="S";
printf("%s",a);
}
那么出现这个问题的原因是什么?
语法错误、运行时错误或其他原因?
将您的代码更改为
#include<stdio.h>
int main()
{
char a;
a='S';
printf("%c",a);
return 0;
}
它会正常工作。
当您使用 %s
调用 printf 时,这意味着 printf
将在给定地址开始打印并在到达空终止符时结束,因为您给 printf 一个 char
而不是 pointer
到 char
,它会尝试使用 a
中写入的值开始打印。
a
是一个占用一个字节的 space 的字符,而在 64 位系统中地址是 8 个字节,所以基本上 printf 取 'a' 中的值和接下来的 7 个字节(随机的 'garbage')并尝试将其用作停止打印的地址。
这就是为什么它有时会像您所说的那样工作,有时这些随机地址可以从中开始打印,但有时它们是您无权访问的地址,例如 OS 使用的内存区域或内核。
要解决这个问题,您需要使 a
成为 char *
而 而不是 成为 char
,并为其分配一个字符串。