Strcpy of C library function learning notes

Source: Internet
Author: User

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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.