"\ 0" in the C ++ string

Source: Internet
Author: User

C ++ does not contain string objects. Strings can be considered as character arrays, but they are different.

Simply put, the difference lies in the last element "\ 0", which indicates whether a string is a string. When a character array is initialized with a string, "\ 0" is appended with the preceding character as an element of the character array.

In the memory, the string is determined based on "\ 0". If the string cannot be found, it will be searched along the character. It occupies memory space, but is not counted in the string length.

When initializing a character array with a string, the system will automatically add a character "\ 0" at the end of the character array. Therefore, the size of the array is larger than the actual number of characters in the string. For example, sizeof (str1) = strlen (str1) + 1;

If the array is initialized with characters, you must put "\ 0" as an element in the initial value table, otherwise it will not become a string.

Char stext [5]; stext [0] = 'a'; stext [1] = 'a'; stext [2] = 'a '; stext [3] = 'a'; stext [4] = '\ 0'; cout <stext <Endl; // The output is 4 A // If the fifth element of the array is stext [4] = 'a'; cout <stext <Endl; // In this way, the output is 5 A and a bunch of garbled characters, and even jumps out of the system error because there is no string Terminator


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.