今天自己在實現strcpy功能時,遇到一個問題,老實顯示出現亂碼:有問題代碼如下:
#include<stdio.h>
char * strcpy(char *to, const char *from)
{
char *save = to;
while(*from)
{
*save = *from;
++save;
++from;
}
// return save;
return to;
}
int main()
{
char c[20];
char * s = "hello,world!" ;
strcpy(c,s);
printf("%s\n",c);
return 0;
}運行結果:
hello,world! (�"
有C開發經驗者一眼就能發現問題所在,而我是對比看了再看才找出問題所在,while循環退出時,save指針指向的字符串數組沒有結束符'\0',導致輸出結果亂碼出現。
知道原因所在,解決起來就簡單了,多種方法:
while((*save = *from))
{
++save;
++from;
}
或者:
while(*from)
{
*save = *from;
++save;
++from;
}
*save = '\0';現在再用其他實現方式來看看,如下:
/*標准的方法之一*/
char * strcpy(char *to, const char *from)
{
char *save = to;
for (; (*to = *from) != '\0'; ++from, ++to);
return(save);
}
char * strcpy1(char *to, const char *from)
{
int i;
for(i=0;(to[i]=from[i]);i++);
return to;
}
char * strcpy2(char *to, const char *from)
{
char * save = to;
while((*to++ = *from++) != '\0');
return save;
}參考網址:
http://bbs.csdn.net/topics/380186525?page=1#post-395300825