Strlen () and strcpy () functions, strlenstrcpy Functions

Source: Internet
Author: User

Strlen () and strcpy () functions, strlenstrcpy Functions

The difference between strlen () and strcpy () functions. One is to return the length of a C-style string, and the other is to copy a C-style string, the two functions are different. In addition, they have some minor differences: The result returned by strlen ("hello") is 5, which isDoes not contain'\ 0', But strcpy (str1, str2 ),Copy'\ 0'.

When using the return value of strlen () to allocate space for the first parameter of strcpy, be sure to pay attention!

For example:

Char * str = "hello ";
Int length = strlen (str );
Char char_array [5];
Strcpy (char_array, str );
Printf ("the new string is: % s \ n", char_array );
Cout <"str's length is:" <length <endl;

In this way, the output length is 5, but the compiler will prompt an error. The VS2010 prompt is:

This indicates that the definition of the string array is small. If the definition is changed to an array of 6, the system returns to normal.

 

When using strcpy, we recommend that you set the size of the target array (the first parameter) to the value of strlen () function return value + 1, or use the following initialization array method:

Char char_array [sizeof ("hello")];
Char * char_array_two = new char [strlen (str) + 1];

 

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.