Read "C + + Primer" (4-1 C and C + + arrays)

Source: Internet
Author: User

Urge reading, summarize the essence, refining notes, a point, there are inappropriate places, welcome message.

Both C and C + + arrays and pointers are low-level composite data types, such as arrays of C + +, like vector containers, and pointers like iterators. Low-level data types have the advantage of being fast. But error prone, not good debugging. Modern C + + programs should be avoided.

Built-in data types-arrays, inconvenient to store variable-length data, defined by fixed lengths (static arrays), arrays like containers, for example, can not know in advance the length of a given array, there is no similar size function to find the length of the array, there is no push_back () function to add elements, if you want to change the array length , the programmer can only re-establish the array and copy the old ones to the new ones.

Remember modern C + + programs, should try to be a vector container to replace the array, to access the same type of data elements, only if the requirements of speed, if the use of the container is not standard, then use the array.

Question 1, array consists of a series of elements of the same type, array declarations include the number and type of array elements, the array is best defined after the initialization.

Declaration of an array

    //[] square brackets indicate that the array is declared, and the number inside indicates the number    of elements contained in the array int states[]; // declares an array    of 50 integers double code[365]; // declaring an array    of 365 floating-point numbers Char chr[]; // declares a 20-character array

Access to the array contents can be denoted by a single element, the subscript number is also called index, which is calculated starting from 0.

Initialization of the array

    // enclosed in curly braces, the elements are separated    by commas. int pow[8] = {1234567  8}; // only standard c,c++ support this initialization syntax     // Pow[0] The first element is assigned a value of 1, etc.

Note: It is best to initialize the array declaration, although it does not error, but as with ordinary variables, using an array without initialization, the value of the elements inside the variable, the garbage value appears.

Array initialization list and size inconsistency

The number of elements in the initialization list and the size of the array are inconsistent, and when the number of initialized elements is less than the size of the arrays, the extra elements are automatically initialized to 0. If the array is not initialized, as with normal variables, the memory that is accessed has garbage values. Initialized, but partially initialized, the compiler automatically initializes the remaining elements to 0. Initialized, but the initialization list element is larger than the array size, then the error is compiled.

    // initialization is not complete, the compiler automatically initializes back to 0    Double d[4] = {1}; // But the vs2010 is compiled and run, all    0 . // error C2078: Too many initializers    Double d[4] = {123456

Array initialization Tips

Omit to fill in the array size, let the compiler automatically determine the actual size of the array and initialize the list of items

    //empty square brackets tell the compiler to initialize the list to determine the actual size of the array    CharChr[] = {'a','b',' ','4'}; //Here's a trick to manually judge the size of an array to be error prone, using the sizeof operator to calculate     for(inti =0; I <sizeof(CHR)/sizeof(chr[0]); i++) {cout<<"i + 1 ="<< Chr[i] <<Endl; }

Note: sizeof (array name) asks for the total size (in bytes) of the array, and sizeof (array "0") asks for an element in the array (in bytes), and the division is the actual size of the array (number of elements).

Array usage tips (constant size)

    Const int 4; // constants represent array sizes, recommended tricks    int Days[num] = {1234}; // good programming style, if you want to modify the size of the array later, you only need to modify the constants    at the beginning  for (int0; index < NUM; index++)    {        << Days[index] << endl;    }

Initializes an array-specified element.

A new feature that belongs to C99, which can be initialized directly to the element specified by the array, and if the last element of the array is initialized, the traditional syntax must be initialized to the last element in sequence before the last element is initialized.

    // initializes the last element to 1    float f[3] = {001};

and C99 rules can be initialized directly.

    // Use square brackets "" to initialize an element of    an array directly int i[3] = {i[2};   ok! Need to add  array name "    "//int in[5] = {[4] = ten}; // Error C2059: Bad Syntax: "["

For normal array initialization, after partial initialization, the remainder is automatically initialized to 0 (here the VS2010 compiler is not, all 0), and if there are other initialization values after the specified initialization element, the values are automatically initialized for subsequent elements of the array. And specifying the value of the initialization element at the first element, the element is also initialized.

For example, in "0" =11 at the 5th (0-5) element position, print the 5th element = 11 at the same time. Specifies that the element of this position is initialized with this value while initializing the specified element.

If an element of an array is initialized more than once, the last one will prevail.

    int inch[7] = {1,2,inch[2] =Ten,3,4,inch[0] = One};//first element i0=11,i5=11    inti;  for(i =0; I <7; i++) {cout<<"I"<< I <<" = "<<inch[I] <<Endl; }

Reading group only

If you only need to read the array and not modify it, the recommended keyword const

Const int Days[num] = {1234}; // each element in the array is treated as a constant, and as with normal variables, the const array needs to be initialized when it is declared.

assigning values to arrays

Use array subscripts (indexes) to assign values to arrays of elements, C and C + + do not support the initialization of global assignments, or simply assign values, and do not support assignment with curly braces (except initialization)

    DoubleD[size] = {1,2,3};//OK this is okay, the list is initialized    intI[size];  for(intCount =0; Count < SIZE; count++) {I[count]=2* COUNT;//OK, use loop and array subscript to assign even values to the elements    }    //i = D;//Error,c does not support array integral assignment//i[size] = d[size];//Error//D[size] = {One, one, and one};//does not work, this form can only be used for initialization, and the assignment must use the index

Boundary Problems for arrays

Do not cross the border (similar to the data type), the array index cannot be crossed, because the compiler does not detect this error. The compiler does not detect the legitimacy of the index, if an illegal index, then the results are unknown, and sometimes interrupted, but there are times can be executed, but the result is very strange (the compiler is different), the compiler does not detect the array boundaries, is out of trust programmer, can save time and efficiency.

Note: Remember that the array count is in principle starting at 0, and the array size is replaced with symbolic constants. Reduce the occurrence of errors.

Then look at the array size designation

You can specify the size in front of an integer constant (unsigned) or a character constant, which is the two methods before C99.

    Const intConst_m =Ten;//in C language (unlike C + +), const values are not considered constants, and in C + +, such defined variables, that is, const constants, can be used to do the dimensions of the array.     intn = -;//defines the variable n    Doubled1[Ten];//OK    Doubled2[5*2+1];//OK    DoubleD3[];//error, no initialization, no size specified    Doubled4[sizeof(int)];//ok,sizeof expression is considered to return an integer constant in C    Doubled5[-Ten];//error C2118: Negative subscript    Doubled6[0];//Error C2466: Cannot allocate an array with a constant size of 0    Doubled7[3.14];//error C2058: constant expression is not an integral type    Doubled8[(int)3.14];//OK    DoubleD9[CONST_M];//error C2057: You should enter a constant expression, "D9" unknown size, cannot allocate an array with a constant size of 0    DoubleD10[n];//error C2057: You should enter a constant expression, "D9" unknown size, cannot allocate an array with a constant size of 0

After C99, the latter two ways are possible, and a new array VLA (variable length array) is created, VLA. The goal is to make C more suitable for numerical calculations.

2. The following syntax is not valid

int ia[get_size ()];

Illegal, get_size () is a function call, not a constant expression, and cannot be used to define the dimensions of an array (the dimension length). Keep in mind that the size of the array must be determined during program compilation, not during runtime.

Issue 3, note the initial values of the following arrays

//IA is a built-in array defined outside the function body, which is the global variable, and the elements are initialized to 0intia[Ten];//SA is an array of element type string and automatically invokes the default constructor of the string class to initialize each element to an empty stringstringsa[Ten];intMainvoid){    //SA2 is an array of element type string and automatically invokes the default constructor of the string class to initialize each element to an empty string    stringsa2[Ten]; //Ia2 is a built-in array defined within the function body, the elements are uninitialized and their values are indeterminate    intia2[Ten]; System ("Pause"); return 0;}

Question 4, do not confuse the array with the vector container

    // vector objects cannot be initialized in this manner.     // vector<int> Ivec = {0, 1, 1, 2, 3, 5, 8};
    int ia3[] = Ivec; // error. You cannot initialize an array with a vector object. 

You can use an initialization list to initialize some or all of the elements of an array when you define an array. If you are initializing all elements, you can omit the array dimension values given in square brackets when you define the array.

If you specify an array dimension, the number of elements provided by the initialization list cannot exceed the dimension value. If the array dimension is greater than the number of initial values listed, only the preceding array element is initialized, and the rest of the other elements, if the built-in type is initialized to 0, if the class type calls the default constructor of the class to initialize.

A character array can be initialized either with a set of character literals enclosed in curly braces, separated by commas, or with a string literal.

Question 5, listing the disadvantages of using arrays instead of vectors

compared to vector types, arrays have the following disadvantages: the length of the array is fixed (before C99), and the array does not provide a size operation to get its capacity, nor does it provide an push_back operation to add elements automatically. Therefore, the programmer cannot know the length of a given array while the program is running, and if the length of the array needs to be changed, the programmer can only create a larger new array and then copy all the elements of the original array into the storage space of the new array. Programs that use built-in arrays are more error-prone and difficult to debug than programs that use the vector type.

Question 6, attention to the array subscript cross-border problem

Similar to vector container, string type, no other method, certain self-study inspection. A common "buffer overflow error" is when writing code, referencing the subscript, without checking the subscript range, resulting in an error!

Read "C + + Primer" (4-1 C and C + + arrays)

Related Article

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.