strcpy问题

扫码查看
本文介绍了strcpy问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 以下代码导致Segementation fault: char * s1; char * s2; s2 =" HELLO"; strcpy(s1,s2); 如果我将代码修改为: char * s1; char * s2; s2 =" HELLO"; s1 =(char *)malloc(10 * sizeof(char)); strcpy(s1,s2); 代码效果很好。所以我应该总是为s1分配内存,然后 我称之为strcpy,对吧? 谢谢。The following code causes "Segementation fault":char *s1;char *s2;s2 = "HELLO";strcpy(s1, s2);If I modify the code to:char *s1;char *s2;s2 = "HELLO";s1 = (char*)malloc(10 * sizeof(char));strcpy(s1, s2);The code works well. So I should always allocate memory for s1, beforeI call strcpy, right?Thanks.推荐答案 不一定。例如, char s1 [128]; char * s2 =" HELLO"; if(strlen( s2)=> sizeof s1)fprintf(stderr,Opps,s2太长了\ n) else strcpy(s1,s2); 关键是目标存储必须存在才能写入 。 malloc()是获取存储空间的一种方式,但是你也可以将写入自动变量或静态变量,只要你确定你这样做就可以了。 不写入结束变量。 - 法律 - 它是一种商品 - Andrew Ryan(环球邮报,2005/11/26)Not necessarily. For example,char s1[128];char *s2 = "HELLO";if (strlen(s2) => sizeof s1) fprintf(stderr, "Opps, s2 is too long\n")else strcpy(s1,s2);The key is that the destination storage must exist before you can writeinto it. malloc() is one way of getting that storage, but you can alsowrite into auto or static variables as long as you make sure you donot write past the end of the variable.--"law -- it''s a commodity"-- Andrew Ryan (The Globe and Mail, 2005/11/26) 是的。一切都必须在某个地方。你必须有一个地方可以放置它, 才能把它放在那里。 - Richard Heathfield Usenet是一个奇怪的地方 - dmr 29/7/1999 http://www.cpax.org.uk 电子邮件:rjh在上面的域名(但显然放弃了www)Yeah. Everything Has To Be Somewhere. You have to have somewhere to put it,before you can put it there.--Richard Heathfield"Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.ukemail: rjh at above domain (but drop the www, obviously) 请参阅comp.lang中的问题7.1,7.2和7.3b .c 常见问题(FAQ)列表 http://www.c-faq.com/ - Er ********* @ sun.comSee Questions 7.1, 7.2, and 7.3b in the comp.lang.cFrequently Asked Questions (FAQ) list http://www.c-faq.com/-- Er*********@sun.com 这篇关于strcpy问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 09:35
查看更多