Character array Assignment "reprint"

Source: Internet
Author: User
Tags array definition

Main ()
{
Char s[30];
strcpy (S, "good news!"); /* Assign string to array */
.
.
.
}
The program at compile time, when encountering Char s[30] This statement, the compiler will be in memory somewhere left
30 bytes in a row, and assigns the address of the first byte to S. When encountering strcpy (strcpy for
Turbo C2.0 function), first create a "good news!/0" string somewhere in the destination file.
where/0 means the string terminates, the terminator is automatically added at compile time, and then a character is re-
To the memory area referred to by S. So when you define a string array, the number of its elements should be at least
1 more length.
Attention:
1. String array cannot be directly assigned with "=", i.e. s= "good news!" is not legal. So should be divided
Different assignment methods for string arrays and string pointers.
2. For long strings, the Turbo C2.0 allows you to use the following methods:
For example:
Main ()
{
Char s[100];
strcpy (S, "the writer would like to thank
"Your interest in he book. He hopes You "
"Can get some helps from the book.");
.
.
.
}


Array of pointers Assign values
 


For example:
Main ()
{
Char *f[2];
int *a[2];
f[0]= "Thank you"; /* Assign value to character array pointer variable */
F[1]= "Good Morning";
*a[0]=1, *a[1]=-11; /* Assign a value to an array of integer pointer variables */
.
.
.
}

--------------------------------------------------------------------------------------------------------------- ---

Add:

Static, local, or global arrays can be initialized only when they are defined, otherwise they must be implemented through other methods, such as loop operations.

Any
int a[3];
static int b[3];
A[3] = {1, 2, 3};
B[3] = {1, 2, 3};
No initialization is wrong at the time of definition!

--------------------------------------------------------------------------------------------------------------- ----

The following is reproduced:
Learning the C language for so many years, I suddenly found that even the string assignment is wrong, really sad.

Char a[10];
How do I assign a value to this array?
1, the definition of the time directly with a string assignment
Char 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!
2. Assigning characters in an array to a value
Char a[10]={' h ', ' e ', ' l ', ' l ', ' o '};
3. Using strcpy
Char 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 is a pointer, but it already points to the stack allocated 10 character space, now this case a again point to the data area of the Hello constant, here pointer a confusion, not allowed!

Also: You cannot use the relational operator "= =" to compare two strings, only with the strcmp () function.


The C-language operator simply cannot manipulate the string. string is treated as an array in the C language, so the strings are restricted in the same way as arrays, and in particular, they cannot be copied and compared using C-language operators.


Attempting to copy or compare a string directly fails. For example, assume that str1 and STR2 have the following declaration:

Char str1[10], str2[10];

It is not possible to use the = operator to copy a string into a character array:

STR1 = "ABC"; /*** wrong ***/

STR2 = str1; /*** wrong ***/

The C language interprets these statements as a (illegal) assignment operation between a pointer and another pointer. However, using the = Initialize character array is legal:

Char str1[10] = "ABC";

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

Trying to compare strings by using relational operators or operator-like operators is legal, but does not produce the expected results:

if (STR1==STR2) .../*** wrong ***/

This statement compares STR1 and str2 as pointers, rather than comparing the contents of two arrays. Because STR1 and str2 have different addresses, the value of the expression str1 = = str2 must be 0.

--------------------------------------------------------------------------------------------------------------- ----------------------

Check the definition of the dynamic array when you are free to use:

It is sometimes unclear how big the array should be. So you want to be able to change the size of the array at run time.
Dynamic arrays can change size at any time.

In layman's words, a static array is a space allocated by the operating system when an array is defined, such as
int a[10];
This is when the system assigns you a space of 10 int in the definition, which can be initialized, such as
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
After this definition, the system allocates 10 storage spaces of type int, and then puts the numbers in the curly braces into these 10 spaces in order. All you have to do is write the sentence, and the array assignment is done by the system. Of course, initialization or not depends on your needs, initialization is not a mandatory operation, you want to initialize the initialization, do not want to have no problem, or the above example continues:
int a[10];
It's defined here, but not initialized, and there's no problem, and you can assign values to it yourself, like
A[1] = 8;
A[5] = 3;
Or
for (int i = 0; i <; i++)
A[i] = i;
Wait a minute

For dynamic arrays, it cannot be initialized because a dynamic array is simply a pointer when defined, such as
int *a;
Here the variable A is just a pointer to the int type, not an array. An array of 10 elements of type int is dynamically allocated, as follows:
A = (int) malloc (10*sizeof (int));
It is clear that pointer a cannot be initialized at the time of definition, such as writing is wrong:
int *a = {1,2,3,4,5,6,7,8,9,10}; /* ERROR! */
Because A is a pointer with only 4 bytes, there is no storage space available for variables that need to be initialized.

--------------------------------------------------------------------------------------------------------------- -------------------------------------

Section III Initializing arrays

1. Initialization of the array

An array can be initialized, that is, when defined, so that it contains values that the program can use immediately.
For example, the following code defines a global array and initializes it with a set of Fibonacci:
    int iarray[10]={1,1,2,3,5,8,13,21,34,55);//initialization
void Main ()
{
//...
}
The value of the initialized array cannot be more than the number of array elements, and the value of the initialized array cannot be omitted by skipping the comma, which is allowed in C, but not in C + +.
For example, the following code is incorrect for initializing an array:
int arrayl[5]={1,2,3,4,5,6}; Error: The number of initialized values is greater than the number of array elements
   int array2[5]={1,,2,3,4};//error: Initialization value cannot be omitted
int array3[5]={1,2,3,}; Error: Initialization value cannot be omitted
int array4[5]={}; Error: Bad syntax format
void Main ()
{
//...
}
The number of initialized values can be less than the number of array elements. When the number of initialized values is less than the number of array elements, the preceding order initializes the corresponding value, followed by the initialization to 0 (global or static array) or to an indeterminate value (local array).
For example, the following program initializes an 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 result of the operation 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
example, the initialization of global arrays and global static arrays is done before the main function is run, while the initialization of local and local static arrays is done after entering the main function.
Global array arrayl[5] The values for the initialization table are sequentially initialized to two, and the values for the elements are initialized to 0 by default.
Global static array array2[5] As with the initialization of global arrays, the initialization table value (1) Represents the value of the 1th element, not all array elements are 1.
The local array arrl[5] is initialized sequentially based on the contents of the initialized table value, and because the initialization table value is only 1, the value of the 4 elements is indeterminate. Here are the values 23567.
The local static array arr2[5] is initialized sequentially based on the initialization table, and the values of the remaining 3 array elements are initialized to 0 by default.

2. Initialize character array

There are two ways to initialize an array of characters, one of which is:
Char array[10]={"Hello"};
The other is:
Char array[10]={' h ', ' e ', ' l ', ' l ', '/0 '};
The first method is widely used, and when initialized, the system automatically fills in the position where the array has no value, '/0 '. In addition, the curly braces in this method can be omitted, that is, can be expressed as:
char array[10]= "Hello";
The second method initializes an array of elements one at a time, as if an array of integers is initialized. This method is typically used to enter invisible characters that are not easily generated on the keyboard.
For example, the following code initializes a value of several tabs:
char charray[5]={'/t ', '/t ', '/t ', '/t ', '/0 ');
do not forget this for the last, '/0 ' Allocate space. If you are initializing a string "Hello", then there are at least 6 array elements for the array it defines.
For example, the following code initializes an array, but causes an unexpected error:
the Code does not cause compilation errors, However, it is dangerous to rewrite the memory cells outside of the array space.

3. Omitting the array size

has an initialized array definition that can omit the array size in square brackets.
For example, the array in the following code is defined as 5 elements:
compilation must know the size of the array. Typically, the number in square brackets when declaring an array determines the size of the array. With an array definition initialized and omitting the size of the array in square brackets, the compiler counts the number of elements between curly braces in order to size the group.    
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}; The
has several benefits for the compiler to derive the size of the initialized array. It is often used to initialize an array of elements that are determined in the initialization, providing an opportunity for programmers to modify the number of elements.
How do you know the size of an array without having to specify the size of the array? The sizeof operation solves the problem. For example, the following code uses sizeof to determine the size of the 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 result of the operation is:
1 2 4) 8 16
The sizeof operation causes the for loop to automatically adjust the number of times. If you want to remove or delete elements from the initialization of a collection of array A, you can simply recompile, and the rest of the content needs to be changed.
The amount of storage that each array occupies can be determined with sizeof operations! sizeof returns the number of bytes for the specified item. sizeof is commonly used in arrays to allow code to be ported between 16-bit machines and 32-bit machines:
For the initialization of strings, be aware that the actual allocated space size of the array is the number of characters in the string plus the end, '/0 ', Terminator.
For example, the following code defines a character array:

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

#include <iostream.h>

void Main ()
{
Char ch[]= "How is You";

cout << "size of array:" <<sizeof (CH) <<endl;
cout << "Size of String:" <<strlen ("How is You") <<endl;
}

The result of the operation is:
Size of Array:12
Size of String:ll
example, the array size is 12, and the string length is 11.
The omitted array size can only be in an array definition that has an initialization.
For example, the following code produces a compilation error:
  int A[];//error: Array size not determined
In the case of defining an array, the compiler must know the size of the array anyway.

Character array Assignment "reprint"

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.