Today, when I implemented the strcpy function, I encountered a problem. I honestly showed garbled characters: the problematic code is as follows:
#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;}
Running result:
hello,world! (�"
If you have experience in C development, you can find the problem at a glance, and I will check the problem again after comparison. When the while LOOP exits, the string array to which the save Pointer Points has no Terminator '\ 0', leading to garbled output.
Knowing the cause is easy to solve. There are multiple methods:
While (* save = * from) {++ save; ++ from;} Or: while (* from) {* save = * from; ++ save; + + from;} * save = '\ 0 ';
Now let's take a look at other implementation methods as follows:
/* One of the Standard Methods */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 ;}
Reference URL:
Http://bbs.csdn.net/topics/380186525? Page = 1 # post-395300825