web*_*oon 2 c segmentation-fault
我写了一些C程序,如下所示.
#include <stdio.h>
#include <string.h>
main() {
char *s1 = "hello world!" ;
char *sto = "it's original string" ;
//copy
strcpy( sto, s1 ) ;
printf( "%s", sto ) ;
}
Run Code Online (Sandbox Code Playgroud)
是的,处理这个问题的文章太多了.我读了每篇文章.所以我发现没有初始化的变量导致错误.
但是,我认为这段代码没有错误,因为sto变量已经初始化为"它是~~ bla bla"的值.
我是关于c的新手,请善待我.谢谢.
在C中,您必须管理存储字符串的存储器.
甲字符串文字,诸如"This is a string"被存储在只读存储器中.
您无法更改其内容.
但是,你可以这样写:
main()
{
char *s1 = "hello world!" ;
// This will allocate 100 bytes on the stack. You can use it up until the function returns.
char sto[100] = "it's original string" ;
//copy
strcpy( sto, s1 ) ;
printf( "%s", sto ) ;
}
Run Code Online (Sandbox Code Playgroud)