Assign a value to a character array

Source: Internet
Author: User
Tags array definition

Main ()
{
Char s [30];
Strcpy (S, "Good news! ");/* Assign a string to the array */
.
.
.
}
When the above program encounters the char s [30] statement during compilation, the Compilation Program will stay somewhere in the memory
Returns the region of 30 consecutive bytes and assigns the address of the first byte to S. When strcpy (strcpy is
For functions of Turbo c2.0), first create a "good news! /0 "string.
Where/0 indicates that the string is terminated, the Terminator is automatically added during compilation, and then repeat one character by one character
To the memory area in S. Therefore, when defining a string array, the number of elements should be at least
Length: 1.
Note:
1. The String Array cannot be directly assigned with "=", that is, S = "good news! "Is invalid. Therefore
Different Assignment Methods for clear string arrays and string pointers.
2. For long strings, Turbo c2.0 agrees to use the following methods:
For example:
Main ()
{
Char s [100];
Strcpy (S, "the writer wocould like to thank you"
"Your interest in his book. He hopes you"
"Can get some helps from the book .");
.
.
.
}


Pointer array assignment
 


For example:
Main ()
{
Char * f [2];
Int * A [2];
F [0] = "thank you";/* assign values to pointer variables of arrays */
F [1] = "good morning ";
* A [0] = 1, * a [1] =-11;/* assign a value to the integer array pointer variable */
.
.
.
}

 

Bytes ------------------------------------------------------------------------------------------------------------------

Supplement:

Whether it's static, local, or global arrays, you can only initialize them when defining them. Otherwise, you must use other methods, such as loop operations.

Whatever
Int A [3];
Static int B [3];
A [3] = {1, 2, 3 };
B [3] = {1, 2, 3 };
Initialization is incorrect when not defined!

Bytes -------------------------------------------------------------------------------------------------------------------

The following is a record:
After learning the C language for so many years, I suddenly found that even the string assignment was wrong, and it was really sad.

Char A [10];
How can I assign a value to this array?
1. assign values directly using strings during definition
Char A [10] = "hello ";
Note: you cannot assign a value to it first, for example, char a [10]; A [10] = "hello"; this is incorrect!
2. assign values to 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:
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 is easy. A is a pointer, however, it has already pointed to the 10-character space allocated in the stack. Now, in this case, A points to the hello constant in the Data zone. The pointer A here is messy and does not agree!

Also, you cannot use the relational operator "=" to compare two strings in bytes. You can only use the strcmp () function to process them.


Operators in C language cannot operate strings at all. In C language, strings are treated as arrays. Therefore, the restrictions on strings are the same as those on arrays. In particular, they cannot be copied or compared using operators in C language.


A direct attempt to copy the string or compare the string will fail. For example, assume that str1 and str2 have the following statement:

Char str1 [10], str2 [10];

It is impossible to copy a string to a character array using the = Operator:

Str1 = "ABC";/***** wrong ***/

Str2 = str1;/*** wrong ***/

The C language interprets these statements as an (invalid) value assignment between a pointer and another pointer. However, using = to initialize the character array is legal:

Char str1 [10] = "ABC ";

This is because in the declaration, = is not a value assignment operator.

Try to use Relational operators or criterion operators to be more legal than the operator string, but will not produce the expected results:

If (str1 = str2).../*** wrong ***/

This statement uses str1 and str2 as pointers for comparison, rather than the content of the two arrays of comparison. Because str1 and str2 have different addresses, the value of str1 = str2 must be 0.

 

 

Certificate -------------------------------------------------------------------------------------------------------------------------------------

When you are free, check the definition of the dynamic array:

It may be unknown whether the array should be large enough. Therefore, you can change the array size during execution.
The dynamic array can be changed at any time.

 

In general, static arrays are the space allocated by the operating system when an array is defined. For example
Int A [10];
This is how the system allocates 10 int-type spaces to you during definition. This space can be initialized, for example
Int A [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
After this definition, the system will first allocate 10 int-type buckets, and then place the numbers in the braces in order into the 10 buckets. All you do is write such a sentence, and the array assignment operation is completed by the system. Of course, initialization depends on your needs. Initialization is not a mandatory operation. If you want to initialize it, You can initialize it. If you don't want it, it's okay. Let's continue with the above example:
Int A [10];
It is defined here, but it is not initialized. No matter what the problem is, you can assign values to it in the future. For example
A [1] = 8;
A [5] = 3;
Or
For (INT I = 0; I <10; I ++)
A [I] = I;
And so on.

Dynamic Arrays cannot be initialized. Because dynamic arrays are only pointers when defined, for example
Int *;
Here, variable A is just a pointer to the int type, not an array. An array with 10 int elements is dynamically allocated, for example:
A = (INT) malloc (10 * sizeof (INT ));
Obviously, pointer A cannot be initialized during definition. For example, writing is wrong:
Int * A = {1, 2, 4, 5, 6, 7, 8, 9, 10};/* error! */
Because a has only four bytes of pointer, there is no available storage space for the variable to be initialized.

Certificate ----------------------------------------------------------------------------------------------------------------------------------------------------

 

Section 3 Initialize an array

1. array Initialization

Array can be initialized, that is, when it is defined, it includes values that can be used immediately by the program.
For example, the following code defines a Global Array and initializes it with a set of Fibonacci numbers:
Int iarray [10] = {,); // Initialization
Void main ()
{
//...
}
The number of initialized array values cannot be more than the number of array elements. The value of initialized array cannot be omitted by skipping commas. This is acceptable in C, however, C ++ does not agree.
For example, the following code initializes an array:
Int arrayl [5] = {1, 2, 3, 4, 5, 6}; // error: the number of initialization values is greater than the number of array elements.
Int array2 [5] = {1, 2, 3, 4}; // error: the initialization value cannot be omitted.
Int array3 [5] = {1, 2, 3,}; // error: the initialization value cannot be omitted.
Int array4 [5] ={}; // error: syntax format Error
Void main ()
{
//...
}
The number of initialization values can be less than the number of array elements. When the number of initialization values is less than the number of array elements, initialize the corresponding values in sequence. The subsequent Initialization is 0 (Global or static array) or an uncertain value (partial array ).
For example, the following program initializes the array:
//*********************
// ** Ch7_2.cpp **
//*********************

# Include <iostream. h>

Int array1 [5] = {1, 2, 3 };
Static int array2 [5] = {1 };

Void main ()
{
Int arr1 [5] = {2 };
Static int arr2 [5] = {1, 2 };

Int N;
Cout <"Global:/N ";
For (n = 0; n <5; n ++)
Cout <"" <array1 [N];

Cout <"/nglobal static:/N ";
For (n = 0; n <5; n ++)
Cout <"" <array2 [N];

Cout <"/nlocal:/N ";
For (n = 0; n <5; n ++)
Cout <"" <arr1 [N];

Cout <"/nlocal static:/N ";
For (n = 0; n <5; n ++)
Cout <"" <arr2 [N];
Cout <Endl;
}

The execution result is:
Global:
L 2 3 0 0
Global static:

1 0 0 0 0
Local:
2 23567 23567 23567 23567
Local static:
1 2 0 0 0
In this example, the initialization of global arrays and Global static arrays is completed before the execution of the main function, and the initialization of local arrays and local static arrays is completed after the entry of the main function.
The value of the Global Array arrayl [5] is initialized to 1, 2, 3 in order for the value of the initialization table, and the value of two elements is initialized to 0 by default.
The initialization of the Global static array array2 [5] is the same as that of the global array. The initialization Table value (1) indicates the value of the 1st elements, rather than that all the array elements are 1.
The local array arrl [5] is initialized in order based on the content of the initialized Table value. Because there are only one initialized Table value, the values of the four elements are uncertain. Here the value is 23567.
The local static array arr2 [5] is initialized in sequence based on the initialization table, and the values of the remaining three array elements are initialized to 0 by default.

2. initialize the character array

There are two methods to initialize the character array:
Char array [10] = {"hello "};
Another type is:
Char array [10] = {'h', 'E', 'l', 'l', '/0 '};
The first method is widely used. during initialization, the system takes the initiative to use the array where no value is filled, and fill in '/0. In addition, curly braces in this method can be omitted, which can be expressed:
Char array [10] = "hello ";
Another method is to initialize an array with an element at a time, as if to initialize an integer array. This method is often used to input invisible characters that are not easy to generate on the keyboard.
For example, the initialization value in the following code is several tabs:
Char charray [5] = {'/t','/0 ');
Do not forget to allocate space for the last, '/0. Suppose you want to initialize a string "hello", the array defined for it has at least six array elements.
For example, the following code initializes the array, but may cause unexpected errors:
Char array [5] = "hello ";
This code will not cause compilation errors, but it is critical because the memory units outside the array space are rewritten.

3. omitted array size

An initialized array definition can omit the array size in square brackets.
For example, the following code defines an array as five elements:
Int A [] = {2, 4, 6, 8, 10 };
  The size of the array must be known during compilation.Usually, the number in square brackets determines the size of the array. If an array definition is initialized and the array size in square brackets is omitted, the compiler calculates the number of elements between curly brackets to obtain the array size.
For example, the following code produces the same result:
Static int A1 [5] = {1, 2, 3, 4, 5 };
Static int A2 [] = {1, 2, 3, 4, 5 };
There are several advantages for the compiler to get the size of the initialization array. It is often used to initialize an array determined by the number of elements in the initialization, providing the opportunity for programmers to change the number of elements.
How can I know the size of an array without specifying the array size? The sizeof operation overcomes this problem. For example, the following code uses sizeof to determine the size of an array:

//*********************
// ** Ch7_3.cpp **
//*********************

# Include <iostream. h>

Void main ()
{
Static int A [] = {1, 2, 4, 8, 16 };
For (INT I = 0; I <(sizeof (a)/sizeof (INT); I ++)
Cout <A [I] <"";
Cout <Endl;
}

The execution result is:
1 2 4 8 16
The sizeof operation enables the for loop to automatically adjust the number of times. If you want to add or delete elements from the set where array a is initialized, you only need to compile it again. Other content does not need to be changed.
The storage space occupied by each array can be determined by sizeof operation! Sizeof returns the number of bytes of the specified item. Sizeof is often used in arrays, so that the code can be transplanted between 16-bit machines and 32-bit machines:
For string initialization, note that the size of the space actually allocated by the array is the number of characters in the string plus the ending character, '/0.
For example, the following code defines an array of characters:

//*********************
// ** Ch7_4.cpp **
//*********************

# Include <iostream. h>

Void main ()
{
Char ch [] = "how are you ";

Cout <"size of array:" <sizeof (CH) <Endl;
Cout <"size of string:" <strlen ("how are you") <Endl;
}

The execution result is:
Size of array: 12
Size of string: LL
In this example, the array size is 12, and the string length is 11.
The omitted array size can only be defined in the initialized array.
For example, the following code will generate a compilation error:
Int A []; // error: the array size is not determined.
When defining an array, the compiler must know the size of the 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.