Methods for assigning a value to a character array

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 is terminated, the Terminator is self-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, Turbo C2.0 agrees to use the following methods:
Like what:
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
 


Like what:
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 have only the ability to initialize when they are defined, otherwise they must be implemented by other means , such as the loop operation.

No matter what
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 very 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";//Such a situation easy to appear, a although is a pointer, but it has been assigned to the stack of 10 character space, and now this case a point to the data area of the Hello constant, where the pointer a appears chaotic, do not agree!

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


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


Attempting to copy or compare a string directly will fail. For example, assume that str1 and str2 have such as 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 a pointer. However, using the = Initialize character array is legal:

Char str1[10] = "ABC";

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

Attempting to use a relational operator or a bitwise operator to compare strings is legal, but does not produce the expected results:

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

This statement takes str1 and str2 as pointers, rather than two of the contents of an array. 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 large an array should be. So you want to have the ability to change the size of the array at execution time.
A dynamic array changes size whenever it is in a row.

In layman's words, static arrays are the space allocated by the operating system when an array is defined, for example
int a[10];
This is when the system assigns you a space of 10 int in the definition, which can be initialized, for example
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Then after this definition, the system allocates 10 storage spaces of type int, and then places the numbers in the braces in the order of the 10 spaces. 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 sample continues:
int a[10];
This is defined here, but not initialized, no matter what the problem, you will be able to assign a value to it, for example
A[1] = 8;
A[5] = 3;
Or
for (int i = 0; i <; i++)
A[i] = i;
Wait a minute

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

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

Section III Initializing arrays

1. Initialization of the array

The array can be initialized, that is, when defined, to include 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 agreed in C, but not in C + +.
For example, the following code is wrong to initialize 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 sequence 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 execution 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 completed before the main function executes, while the initialization of local and local static arrays is completed 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 a global array, 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, because the initialization table value is only 1, so there are 4 elements whose values are 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"};
There is one more:
    Char array[10]={' h ', ' e ', ' l ', ' l ', '/0 '};
The first method is widely used, when initialized, the system itself actively in the array is not filled with the location, '/0 ' to fill up. In addition, the curly braces in such a method can be omitted, which can be expressed as:
    Char array[10]= "Hello";
Another method initializes an array of elements at a time, as if an array of integers is initialized. Such methods are often used to enter the invisible characters that are not easy to generate on the keyboard.
For example, the following code initializes the values to several tabs:
   char charray[5]={'/t ', '/t ', '/t ', '/t ', '/0 ');
Don't forget to allocate space for the last, '/0 '. Suppose you want to initialize a string "Hello", which has at least 6 array elements for the array it defines.
For example, the following code initializes an array, but causes an unexpected error:
Char array[5]= "Hello";
This code does not cause compilation errors, but is critical because it overwrites memory cells outside of the array space.

3. Omit array size

An array definition with initialization can omit the size of the array in square brackets.
For example, in the following code, the array is defined as 5 elements:
 int a[]={2,4,6,8,10};
  the size of the array must be known at compile time. in general, the number in square brackets when declaring an array determines the size of the array. With an initialized array definition and omitting the size of the array in square brackets, the compiler counts the number of elements between the 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};
There are several advantages to having the compiler 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 the program ape to change 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 overcomes 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 execution is:
1 2 4) 8 16
The sizeof operation causes the for loop to adjust its own number of times. Suppose you want to delete elements from the set of initialization a array, just need to compile again, and nothing else needs to be changed.
The amount of storage that each group occupies can be determined with sizeof operations! sizeof returns the number of bytes for the specified item. sizeof is often 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 execution 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 the array definition with initialization .
For example, the following code will produce 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.

Methods for assigning a value to a 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.