How to assign a value to a character array

The original address is: Method of assigning value to character array

main()
{
char s[30];
strcpy(s, "Good News!"); /*Assign a string to the array*/
.
.
.
}
When the above program is compiled, it encounters the statement char s[30] , the compiler will set aside
a , and assign the address of the first byte to s. When encountering strcpy (strcpy is
a function of Turbo C2.0), first create a "Good News!/0" string somewhere in the object file.
Where /0 means the string is terminated, the terminator is automatically added at compile time, and then copied character by
character to the memory area pointed to by s. Therefore, when defining a string array, the number of elements should be at least 1 more than the
length .
Note:
1. String arrays cannot be directly assigned with "=", that is, s="Good News!" is illegal. Therefore,
the .
2. For long strings, Turbo C2.0 allows the following methods:
For example:
main()
{
char s[100];
strcpy(s, "The writer would like to thank you for"
"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 a value to a char array pointer variable*/
f[1]="Good Morning" ;
*a[0]=1, *a[1]=-11; /*Assign an integer array pointer variable*/
.
.
.
}

 

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

Replenish:

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

Any
int a[3];
static int b[3];
a[3] = {1, 2, 3};
b[3] = {1, 2, 3};
not initialized at definition time is an error!

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

The following is reproduced:
After learning the C language for so many years, I suddenly found that even the assignment of strings is wrong, which is really sad.

char a[10];
How to assign value to this array? 1. When defining, assign char a[10]="hello"
directly with a string ; Note: You cannot define and then assign a value to it, such as char a[10]; a[10]="hello"; this is wrong ! 2. Assign 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] also does not exist!
2. char a[10]; a="hello";//This situation is easy to occur. Although a is a pointer, it has already pointed to the 10 character space allocated in the stack. Now in this case, a points to the data area. The hello constant, the pointer a here is confused, it is not allowed!

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


Operators in C language cannot operate on strings at all. Strings are treated as arrays in C, so strings are restricted in the same way as arrays, in particular, they cannot be copied or compared using C operators.


Direct attempts to copy or compare strings will fail. For example, suppose str1 and str2 have the following declarations:

char str1[10], str2[10];

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

str1 = "abc";     /*** WRONG ***/

str2 = str1;       /*** WRONG ***/

The C language interprets these statements as (illegal) assignments between one pointer and another. However, it is legal to initialize a character array with =:

char str1[10] = "abc";

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

Attempting to compare strings using relational or equality operators is legal, but will not produce the expected result:

if (str1==str2) ...    /*** WRONG ***/

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

 

 

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

Check the definition of dynamic array when you have time:

Exactly how large the array should be, sometimes it may not be known. So hoping to have the ability to change the size of the array at runtime.
Dynamic arrays can change size at any time.

 

In layman's terms, a static array is the space allocated by the operating system when the array is defined, such as
int a[10];
this means that the system allocates 10 int-type spaces to you at the time of definition, and this space can be initialized , such as
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
then after this definition, the system will first allocate 10 int type storage spaces, and then put The numbers in the curly brackets are placed in the 10 spaces in order. All you do is write such a sentence, and the operation of the array assignment is completed by the system. Of course, whether to initialize or not depends on your needs. Initialization is not a mandatory operation. If you want to initialize, you can initialize. If you don’t want to, it’s no problem. The above example continues:
int a[10];
is defined here, but it is not initialized, so there is no problem. , you can assign values ​​to it later, such as
a[1] = 8;
a[5] = 3;
or
for(int i = 0; i < 10; i++)
    a[i] = i;
etc.

For dynamic arrays , cannot be initialized, because the dynamic array is just a pointer when it is defined, such as
int *a;
here the variable a is just a pointer to an int type, not an array. Dynamically allocate an array of 10 elements of type int, as follows:
a = (int) malloc(10*sizeof(int));
Obviously, the pointer a cannot be initialized when it is defined. For example, it is wrong to write:
int * a = {1,2,3,4,5,6,7,8,9,10}; /* Error! */
Because a is a pointer of only 4 bytes, there is no storage space available for variables that need to be initialized.

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

 

The third section initializes the array

1. array initialization

  Arrays can be initialized, that is, when they are defined, to contain values ​​that the program can use immediately.
  For example, the following code defines a global array and initializes it with an array of Fibonacci numbers:
    
int iArray[10]={1, 1, 2, 3, 5, 8, 13, 21, 34, 55); //initialize
    void main()
    {       //...     }


  The number of initialized array values ​​cannot exceed the number of array elements, and the initialized array values ​​cannot be omitted by skipping commas. This is allowed in C, but in Not allowed in C++.
  For example, the following code is wrong to initialize an array:
    int arrayl[5]={1, 2, 3, 4, 5, 6}; //error: there are more initialization values ​​than 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: syntax error
    void main()
    {       //...     }


  The number of initialization 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 corresponding values ​​are initialized in sequence in the front, and the latter are initialized to 0 (global or static array) or 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 running 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 the example, the initialization of the global array and the global static array is done before the main function runs, and the initialization of the local array and the local static array is Done after entering the main function.
  The global array arrayl[5] is initialized to 1, 2, and 3 in order for the values ​​of the initialization table, and the values ​​of the other two elements are initialized to 0 by default.
  The global static array array2[5] is the same as the initialization of the global array. The initialization table value (1) represents the value of the first element, not that all array elements are 1.
  The local array arrl[5] is initialized in order according to the contents of the initialization table value. Since there is only one initialization table value, the values ​​of the remaining 4 elements are uncertain. Both here are the value 23567.
  The local static array arr2[5] is initialized in sequence according to the initialization table, and the values ​​of the remaining three array elements are initialized to 0 by default.

2. initialize character array


  There are two ways to initialize a character array, one is: char array[10]={"hello"};  the other is: char array[10]={'h','e','l','l ','/0'};  The first method is widely used. During initialization, the system automatically uses it in the position where the array does not have a value, and '/0' fills it. In addition, the curly braces in this method can be omitted, that is, it can be expressed as: char array[10]="hello"; the  second method initializes the array one element at a time, just like initializing the integer array. This method is often used to enter those invisible characters that are not easily generated on the keyboard.   For example, the following code initializes several tab characters:  char chArray[5]={'/t','/t','/t','/t','/0') ;   don't forget here Allocate space for the last, '/0'. If you want to initialize a string "hello", the array defined for it has at least 6 array elements.   For example, the following code initializes an array, but causes an unexpected error:     char array[5]="hello";  this code does not cause a compilation error, but is dangerous because it overwrites memory locations outside the array space . 3. omit array size
    

    

    


   







  An array definition with initialization can omit the array size in square brackets.
  For example, the following code defines an array with 5 elements:
    int a[]={2, 4, 6, 8, 10};
  the size of the array must be known at compile time. In general, the number within square brackets when declaring an array determines the size of the array. When there is an initialized array definition and the array size in square brackets is omitted, the compiler counts the number of elements between the curly braces to find the size of the array.
  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};

  let the compiler Deriving the size of the initialized array has several benefits. It is often used to initialize an array whose number of elements is determined during initialization, providing the programmer the opportunity to modify the number of elements.
  How to know the size of the array without specifying the size of the array? The sizeof operation solves 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 running result is:
    1 2 4 8 16
The   sizeof operation makes the for loop automatically adjust the number of times. If you want to add or remove elements from the collection that initializes the a array, you only need to recompile, and nothing else needs to be changed.
  The amount of storage occupied by each array can be determined using the sizeof operation! sizeof returns the number of bytes for the specified item. sizeof is often used for arrays to make the code portable between 16-bit machines and 32-bit machines:
  for string initialization, it should be noted that the size of the actual allocated space for the array is the number of characters in the string plus the end, '/0' , the terminator.
  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 result is:
    size of array :12
    size of string:

  In the example, the size of the array is 12, and the length of the string is 11.
  Omitting the array size can only be done in an initialized array definition .
  For example, the following code will generate a compilation error:
    int a[]; //error: array size not determined
  In the case of an array being defined, the compiler must know the size of the array anyway.

 


Please indicate the address of this article when reprinting: Method of assigning value to character array

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324036814&siteId=291194637