Read "c ++ primer" thin (4-1 c and c ++ arrays), "cprimer" 4-1

Source: Internet
Author: User

Read "c ++ primer" thin (4-1 c and c ++ arrays), "cprimer" 4-1

Supervise reading, summarize the essence, extract notes, and inspire others. If you have any questions, leave a message to correct them.

Arrays and pointers of c and c ++ belong to low-level Composite data types, such as arrays of c ++, similar to vector containers, and pointers similar to iterators. The advantage of low-level data types is that the speed is fast. But it is prone to errors and debugging is not good. Modern c ++ programs should be avoided.

Built-in data type-array, which is inconvenient to store variable-length data. After definition, the length is fixed (static array). arrays are similar to containers. For example, you cannot know the length of a given array in advance, there is no function similar to the size function to evaluate the array length, and no push_back () function to add elements. To change the array length, the programmer can only create an array and copy the old one to the new one.

Remember that modern c ++ programs should try to replace arrays with vector containers to access data elements of the same type. If the container is not up to standard, then use the array.

Problem 1: array is composed of a series of elements of the same type. The array declaration includes the number and type of array elements. It is best to define the array before initialization.

Array declaration

// [] Square brackets indicate that an array is declared. The number of elements contained in the array indicates the number of int states [50]. // declare an array of 50 integers double code [365]; // declare an array of 365 floating-point numbers char chr [20]; // declare an array of 20 characters

When accessing the array content, you can use subscript to represent a single element. The subscript number is also called index and starts from 0.

Array Initialization

// Enclose the elements in curly brackets. Use commas to separate int pow [8] = {1, 2, 3, 4, 5, 6, 7, 8 }; // only standard c and c ++ support this initialization syntax. // the value of the first element of pow [0] is 1, and so on.

Note: It is best to initialize an array declaration. Although no error is reported, like a common variable, an uninitialized array is used. The element value in the array is not fixed and spam value is displayed.

Inconsistent array initialization list and size

The number of elements in the initialization list is inconsistent with the array size. When the number of initialization elements is smaller than the array size, the redundant elements are automatically initialized to 0. If the array is not initialized, the original junk value of the accessed memory is the same as that of the common variable. Initialization, but partial initialization, the compiler will automatically initialize the remaining elements to 0. If the initialization list element is larger than the array size, an error is returned.

// Initialization is not complete. The Compiler automatically initializes the code to 0 double d [4] = {1}; // However, the code is compiled and run in vs2010, all of which are 0 // error C2078: too many initial values: double d [4] = {1, 2, 3, 4, 5, 6 };

Array initialization tips

The array size is omitted so that the compiler can automatically determine the actual size of the array and the items in the initialization list.

// Empty square brackets tell the compiler to determine the actual size of the array in the initialization list char chr [] = {'A', 'B', '', '4 '}; // here we need a technique to manually determine the array size which is prone to errors. We use the sizeof operator to calculate for (int I = 0; I <sizeof (chr)/sizeof (chr [0]); I ++) {cout <"I + 1 =" <chr [I] <endl ;}

Note: sizeof (array name) is used to calculate the total size of an array (in bytes), and sizeof (array [0]) is used to calculate the size of an element in an array (in bytes ), division is the actual size of the array (number of elements ).

Tips for using arrays (constant size)

Const int NUM = 4; // a constant represents the array size. Recommended tips: int days [NUM] = {1, 2, 3, 4}; // a good programming style, if you want to modify the array size in the future, you only need to modify the constant starting with for (int index = 0; index <NUM; index ++) {cout <days [index] <endl ;}

Initialize the specified element of the array.

It is a new feature of C99 and can be directly initialized to the elements specified by the array. If the last element of the array is initialized, the traditional syntax must be initialized to the last element in sequence, to initialize the last element.

// Initialize the last element as 1 float f [3] = {0, 0, 1 };

C99 requires that initialization can be performed directly.

// Use square brackets [] to initialize int I [3] = {I [2] = 100} for an element in the array. // OK! You need to add the array name [] // int in [5] = {[4] = 10}; // error C2059: syntax error: "["

For general array initialization, after some initialization, the remaining automatic Initialization is 0 (here, the vs2010 compiler is not like this, all are 0 ), if there are other initialization values after the specified initialization element, these values are automatically initialized to the subsequent elements of the array, and the value of the initialization element is specified at the first element, this element will also be initialized.

For example, if in [0] = 11 is at the position of 5th (0-5) elements, 5th elements = 11 are printed at the same time. It means that the specified element is initialized, And the element at the current position is also initialized using this value.

If an array element is initialized multiple times, the last time prevails.

Int in [7] = {1, 2, in [2] = 10, 3, 4, in [0] = 11}; // The first element i0 = 11, i5 = 11 int I; for (I = 0; I <7; I ++) {cout <"I" <I <"=" <in [I] <endl ;}

Read-Only Array

If you only need to read the array without modifying it, the recommendation keyword const

Const int days [NUM] = {1, 2, 3, 4}; // each element in the array is treated as a constant, just like a common variable, the const array also needs to be declared during initialization.

Array assignment

Use array subscript (INDEX) to assign values to array elements. c and c ++ do not support initialization of the overall assignment, or simply assign values, you cannot assign values to the list enclosed by curly brackets (except for initialization)

Double d [SIZE] = {1, 2, 3}; // OK this is acceptable. The list initializes int I [SIZE]; for (int count = 0; count <SIZE; count ++) {I [count] = 2 * count; // OK, use the loop and array subscript to assign an even value to the array element} // I = d; // error, c does not support the overall array assignment // I [SIZE] = d [SIZE]; // error // d [SIZE] = {11, 22, 33 }; // does not work. This mode can only be used for initialization, and indexes must be used for value assignment.

Array Boundary Problems

Never cross-border (similar to data types). array indexes cannot cross-border, because the compiler will not detect such errors. The compiler does not check the validity of the index. If an invalid index occurs, the result is unknown, sometimes interrupted, but sometimes executable, but the result is strange (the compiler is different ), the compiler does not detect the array boundary. It is out of trust for programmers and can save time and efficiency.

Note: Remember, the array count starts from 0 in principle, and the array size is replaced by a symbolic constant. Reduce errors.

Then, let's look at the specified array size.

You can specify the size with an integer constant (unsigned) or a character constant before C99.

Const int const_m = 10; // in c Language (different from c ++), the const value is not considered as a constant. In c ++, such Defined variables are, that is, the const constant, which can be used as the dimension of the array. Int n = 100; // defines the Variable n double d1 [10]; // OK double d2 [5*2 + 1]; // OK double d3 []; // error, no initialization, and no size specified for double d4 [sizeof (int)]; // OK, the sizeof expression is considered to return an integer constant double d5 [-10] in c; // error C2118: Negative subscript double d6 [0]; // error C2466: the array double d7 [3.14] with a constant size of 0 cannot be allocated; // error C2058: the constant expression is not an integer double d8 [(int) 3.14]; // OK double d9 [const_m]; // error C2057: constant expression should be input, "d9" unknown size, cannot be allocated array double d10 [n] whose constant size is 0; // error C2057: constant expression, "d9" unknown size, cannot be allocated an array whose constant size is 0

After c99, the last two methods can be used, and a new array VLA (variable length array) is created to become a variable-length array, VLA. The purpose is to make c more suitable for numerical calculation.

Question 2: The following syntax is invalid

int ia[get_size()];

Invalid. get_size () is a function call, not a constant expression. It cannot be used to define the dimension (dimension length) of an array ). Remember, the size of the array must be determined during program compilation.

Problem 3: Pay attention to the initial values of the following Arrays

// Ia is a built-in array defined in the function body, that is, a global variable. Each element is initialized as 0int ia [10]; // sa is an array of string element type, automatically call the default constructor of the string class to initialize each element as a Null string sa [10]; int main (void) {// sa2 is an array of the string type, automatically call the default constructor of the string class to initialize each element as a Null string sa2 [10]; // ia2 is a built-in array defined in the function body, and each element is not initialized, int ia2 [10]; system ("pause"); return 0 ;}

Problem 4: Do not confuse arrays with vector containers

// The vector object cannot be initialized in this way. // Vector <int> ivec = {0, 1, 1, 2, 3, 5, 8 };
Int ia3 [] = ivec; // error. Arrays cannot be initialized using vector objects.

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

If the array dimension is specified, the number of elements in the initialization list cannot exceed the dimension value. If the array dimension is greater than the number of initial values of the listed elements, only the previous array elements are initialized, and the remaining elements are initialized to 0 if they are of built-in type, if it is a class type, the default constructor of the class is called for initialization.

Character Arrays can be initialized with a set of character denominations enclosed by curly brackets and separated by commas (,) or a string nominal value.

Problem 5. disadvantages of listing arrays instead of Vectors

Compared with the vector type, arrays have the following Disadvantages: the array length is fixed (before C99), and the array does not provide the size operation to obtain its capacity, it does not provide the push_back operation for automatically adding elements. Therefore, the programmer cannot know the length of a given array when running the program. If you need to change the length of an array, the programmer can only create a larger new array, copy all elements of the original array to the bucket of the new array. Compared with programs of the vector type, programs with built-in arrays are more error-prone and difficult to debug.

Problem 6: array subscript out of bounds

Similar to the vector container, which belongs to the string type, you must perform self-check. A common "buffer overflow error" means that when writing code, it references a subscript that is out of bounds and does not check the range of the lower mark, resulting in an error!

 

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.