Assignment of a [to] character array

Source: Internet
Author: User

Reference Original address: http://blog.chinaunix.net/uid-26404201-id-3212247.html

Defines an array of char a[10];

How do I assign a value to this array? 1, the definition of the time directly with a string assignmentchar a[10]= "Hello";Note: You cannot define and assign a value to it first, such as Char a[10]; a[10]= "Hello"; this is wrong! Char a[10]; a[]= "Hello"; it's also wrong! 2. Assigning characters in an array to a valueChar a[10]={' h ', ' e ', ' l ', ' l ', ' o '};3. Using strcpyChar a[10]; strcpy (A, "Hello");error-prone situation:1, Char a[10]; a[10]= "Hello";//How can a character hold a string? Moreover a[10] also does not exist! 2, Char a[10]; a= "Hello";//This situation is easy to appear, a although a pointer, but it already points to the 10-character space allocated in the stack, now this case a again point to the hello constant in the data area, where pointer A is chaotic, not allowed! Main ()
{
Char s[30];
strcpy (S, "good news!"); /* Assign a string to the array */.
}
At compile time, when the program encounters Char S[30] This statement, the compiler leaves a contiguous 30-byte area somewhere in memory and assigns the address of the first byte to S. When a strcpy (strcpy is a function of the turbo C2.0) is encountered, a "good news!/0" string is first created somewhere in the destination file. where/0 means the string is terminated, the Terminator is automatically added at compile time, and a character Fu is copied to the memory area referred to by S. Therefore, when defining a string array, the number of elements should be at least 1 more than the length of the string.

Assignment of a [to] character array

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.