How to assign a value to this array?
1. definition, directly use the string assignment.
Char a[ 10]= "Hello";
Note: it cannot be defined before assignment, such as char a [10]; A[ 10]= "Hello"; This is not right!
2. Assign values to the characters in the array one by one.
char a[ 10]={'h ',' e ',' l ',' l ',' o ' };
3. use strcpy
char a[ 10]; Strcpy(a, "Hello");
Error-prone situation:
1、char a[ 10]; A[ 10]= "Hello"; //How can a character hold a string? Besides, a[ 10] does not exist!
2、char a[ 10]; A= "hello"; //This situation is easy to happen. Although a is a pointer, it has pointed to the allocated 10 character space in the stack. Now in this case, a points to the hello constant in the data area. The pointer A here is confusing and is not allowed!
Master ()
{
char s[30];
Strcpy(s, "Good news!" ); /* Assign a string to an array */.
}
When compiling the above program, when encountering the statement char s[30], the compiler will leave a continuous 30-byte area somewhere in the memory, and assign the address of the first byte to S. When encountering strcpy( strcpy is a function of Turbo C2.0), the first is a "good news! /0 "string. Where /0 indicates the termination of the string, the terminator is automatically added at compile time, and then copied to the memory area pointed by S character by character. Therefore, when defining a string array, the number of elements should be at least 1 more than the length of the string.