Test Question 2 string copy function char * strcpy (char * strdst, const char * strsrc)

Source: Internet
Author: User

The prototype of the string function is char * strcpy (char * strdst, const char * strsrc)

 

Char * strcpy (char * strdst, const char * strsrc) // use const to indicate that the original string cannot be changed. In addition, use const to indicate that * strscr is the input parameter.

{

Char * address = strdst; // Save the first address of the target string, because the strdst pointer is moving next, not pointing to the first address of the string.

If (strdst = NULL | strsrc = NULL)

Return NULL;

If (strdst = strsrc)

Return strdst;

While (* strdst ++ = * strsrc ++ )! = '\ 0');/Note that the semicolon ends here.

Return address;

}

 

Note:

1. The original string content cannot be changed in the function. Therefore, it should be declared as the const type.

2. to judge whether the source pointer or target pointer is null, be rigorous in thinking and consider exceptions.

3. consider pointing the destination pointer to the same address as the original pointer, so that you do not need to copy it. You can directly return any of the addresses.

4. If the return value of the function is the first address of the target string, the return type or character pointer should be considered to copy the return value of the function for other operations.

5. when copying a string, there are two methods: first copy to judge whether the character is null (the code above is this method) or first judge whether the character is null, then copy and add the '\ 0' character at the end (its value is 0, that is, the ASCII value is 0)

Char * strcpy (char * strdst, const char * strsrc)

{

Char * address = strdst;

If (strdst = NULL | strsrc = NULL)

Return NULL;

If (strdst = strsrc)

Return strdst;

While (* strsrc! = '\ 0 ')

{

* Strdst ++ = * strsrc ++;

}

* Strdst = '0 ';

Return address;

}

 

 

 

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.