Write C + + program to implement strcpy () function

Source: Internet
Author: User

Read this question on the Internet and write the following procedure:

Code Listing 1:

Char *cpystr (char *des,const char *src)
{
int i = 0;
if (NULL = = des | | NULL = = src)
return NULL;
while (src[i]! = ' + ')
{
Des[i] = Src[i];
i++;
}

Return des;
}

1. This write can implement the replication function, except that C + + syntax has a vulnerability, support const char* to char * default conversion, if the call

Cpystr () writes like this: Cpystr ("Hello", "Hello"), can be compiled through (tested under VS2013). A segment error occurred while running.

To avoid this error, you can define a function as follows:,

Char *cpystr (const char *des,const char *SRC)

printf ("Error:the first arg can ' t be const\n");

Exit (0);

If the knowledge Declaration is Char *cpystr (const char *des,const char *src), and the function is not defined, an error occurs.

"Error LNK2019: unresolved external symbol" char * __cdecl cpystr (char const *,CHAR const *) "([email Protected]@[email protected]),

The symbol is referenced in the function _main. ”

2. As stated above, for Cpystr (char *des,const char *src) the parameter cpystr ("Hello", "Hello"), the first parameter of first argument const char * is converted to

char *, compilation can be passed. You need to use a function overload to define another function cpystr (const char *des,const char *SRC) to resolve.

Code Listing 2:

const char *a = "Hello";
char *b = A;

Code 2 cannot be compiled under VS2013, the error C2440: "Initialization": cannot be converted from "const char *" to "char *"

3. The above code 1 and code 2 are written in the C language compiled results are the same as the C + + compilation (test with GCC), but the C language cannot carry out function overloading to avoid this error.

Write C + + program to implement strcpy () function

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.