C language--character array

Source: Internet
Author: User

In C language programming, we typically use a character array to hold a string. For example, we want to store the string "http://i.cnblogs.com", which has a total of 20 characters, to hold the string, we need a 21-length character array. Why 21 instead of 20? In the C language, the array of strings is terminated by default, so we need a character array of length 21 to store the variable.

unsigned char text[21] = "http://i.cnblogs.com";

Now that we know how to store a string, let's discuss a few other issues. First, a character array is known to hold a string, how long does it solve the string? To solve this problem, we should start with the storage principle of string. In the previous article, we have known that the character at the end of the storage string is ' \ s ', then we can use the loop to scan the character array to scan the ' s ' as the end flag, thus solving the length of the string.

unsigned char get_text_length (unsigned char *sp)

{

unsigned char text_length=0;

while (*SP)/* Determines if the character is ' \ s ' */

{

text_length++;

*sp++; /* Point to the next one in the array */

}

return text_length;

}

Furthermore, with regard to the initialization of character arrays, can we use double quotation marks to directly assign values to strings while declaring the array of characters, and is there any other way?

Method One:

unsigned char text[] = "www.google.com";

Method Two:

unsigned char text[20];

strcpy (text, "www.google.com");

Note that method two calls the system function strcpy (), which is defined in string.h.

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.