Array and pointer of C ++ Primer version 4 Reading Notes (3), primer version 4

Source: Internet
Author: User
Tags array definition

Array and pointer of C ++ Primer version 4 Reading Notes (3), primer version 4

The C ++ language provides two low-level composite types similar to the vector and iterator types-arrays and pointers. Similar to the vector type, Arrays can also store a group of objects of a certain type. The difference between them is that the length of the array is fixed. Once an array is created, new elements cannot be added. Pointers can be used to traverse and check elements in the array like the iterator.

Modern C ++ programs should try to use vector and iterator types, instead of low-level arrays and pointers. Well-designed programs only use arrays and pointers within the class implementation when speed is emphasized.

An array is a built-in data structure similar to the vector type in the standard library in C ++. Like vector, array is also a container that stores a single data type object. Each object has no separate name, but is accessed by its position in the array.

Compared with the vector type, arrays have a significant defect in that the length of an array is fixed and programmers cannot know the length of a given array. The array does not have the size operation, nor does the push_back operation provide the ability to automatically add elements to it. If you need to change the length of the array, the programmer can only create a larger new array, and then copy all elements of the original array to the new array space.

I. Array

An array is a composite data type consisting of the type name, identifier, and dimension. The type name specifies the type of elements stored in the array, while the dimension specifies the number of elements contained in the array.

Note: The type name in the array definition can be a built-in data type or class type. In addition to reference, the type of the array element can also be any composite type. Not all elements are referenced arrays.

1.1 array definition and initialization

The dimension of the array must be defined by a constant expression with a value greater than or equal to 1. This constant expression can only contain an integer literal value constant, an enumerated constant, or an integer const object initialized using a constant expression. Non-const constants and const variables whose values are known only during the running stage cannot be used to define the dimension of the array.

1.1.1 explicitly initialize array elements

When defining an array, you can provide a set of initial values separated by commas (,) for its elements. These initial values are enclosed in curly brackets {} to form a publish list.

If the element initial value is not explicitly provided, the array elements are initialized like normal variables:

1. built-in arrays defined in function external, whose elements are initialized to 0;

2. built-in arrays defined in the function body, whose elements are not initialized;

3. No matter where the array is defined, if its element is of the class type, the default constructor of the class is automatically called for initialization. If the class does not have the default constructor, the array must be explicitly initialized.

Note: unless the initial element values are explicitly provided, the elements of the built-in local array are not initialized. In this case, except for assigning values to elements, other operations that use these elements are not defined.

1.1.2 special character array

Character Arrays can be initialized with a set of character denominations enclosed by curly brackets and separated by commas (,) or a string nominal value. However, note that the two initialization modes are not identical. The string literal value contains an additional null character (null) used to end the string. When the new array is initialized using the string literal value, it is assumed null characters in the new array.

1.1.3 direct copying and assignment of arrays not allowed

Unlike vector, an array cannot be initialized with another array or assigned to another array. These operations are invalid.

1.2 Array Operations

Like vector elements, array elements can be accessed using subscript operators, and array elements are counted from 0.

1.2.1 check the array tag Value

Just like the string and vector types, when using arrays, the programmer must also ensure that the value under it is within the correct range, that is, the array corresponds to an element at the subscript position.

II. Introduction of pointers

Vector traversal can be implemented by subscript or iterator. Likewise, you can use subscript or pointer to traverse arrays. A pointer is a composite data type pointing to an object of a certain type. It is an iterator used for Arrays: pointing to an element in an array. Use the unreferenced operator * and the auto-incrementing operator ++ on the pointer to the array element, which is similar to the usage on the iterator. To obtain the value of the object pointed to by the pointer. When the pointer is auto-incrementing, the pointer is moved to point to the next element in the array.

2.1 What is a pointer

The pointer concept is simple: a pointer is used to point to an object. Like the iterator, pointers provide indirect access to the objects they refer to, but the pointer structure is more generic. Unlike the iterator, the pointer is used to point to a single object, and the iterator can only be used to access elements in the container.

Specifically, the pointer stores the address of another object.

2.2 pointer definition and initialization

Each pointer has a data type associated with it, which determines the type of the object to which the Pointer Points.

2.2.1 definition of pointer Variables

String * pstring;

String * p1, * p2, p3;

2.2.2 another method for declaring pointers

String * ps;

String * p1, p2;

2.2.3 continuous declarations of multiple pointers may cause confusion

Generally, the pointer style is defined as follows: place the symbol * closely following the pointer variable name.

2.2.4 possible pointer values

A valid pointer must be one of the following three States: Save the address of a specific object, point to another object after an object, or 0. If the pointer saves a value of 0, it indicates that it does not point to any object. The uninitialized pointer is invalid until it is assigned a value.

2.2.5 avoid using Uninitialized pointers

For most compilers, if Uninitialized pointers are used, the undefined values in the pointers are considered as addresses, and the bit content stored in the memory address is manipulated. Using Uninitialized pointers is equivalent to manipulating the basic data stored in this uncertain address. Therefore, resolving Uninitialized pointers usually causes program crash.

2.2.6 constraints on Pointer initialization and assignment

(1) constant expression with 0 values;

(2) Address of the Type-matched object;

(3) next address at the end of another object;

(4) another pointer of the same type.

2.2.7 void * pointer

C ++ provides a special pointer type void *, which can save the address of any type of object.

The void * pointer only supports several limited operations: compare it with the other pointer through the line; pass the void * pointer to the function or return the void * pointer from the function; assign a value to the other void * pointer. You cannot use the void * pointer to manipulate the object to which it points.

2.3 pointer operation

2.3.1 dereference operations for generating left values

Returns the left value of the specified object. You can use this function to modify the value of the object indicated by the pointer.

2.3.2 comparison between pointer and reference

Although both references and pointers can indirectly access another value, there are two important differences between them.

1. The reference always points to an object: There is no initialization error when defining the reference.

2. Differences in Value assignment: assigning a value to a reference modifies the value of the object associated with the reference, rather than associating the reference with another object.

Once the reference is initialized, it always points to the same specific object.

2.3.3 pointer to pointer

2.4 access array elements with pointers

In C ++, pointers are closely related to arrays. When an array name is used in an expression, the name is automatically converted to a pointer pointing to the first element of the array.

2.4.1 arithmetic operations on pointers

You can calculate the pointer value pointing to another element of the array by adding (or subtracting) an integer value to the pointer to an element of the array.

Generally, adding (or subtracting) an integer value n on the pointer is equivalent to getting a new pointer. The new Pointer Points to the element that the pointer originally points to (or before) the Nth element.

Add or subtract 0 from the pointer to keep the pointer unchanged. More interestingly, if a pointer has a value of 0 (NULL pointer), it is still valid to add 0 to the pointer, and the result is a pointer with another value of 0. You can also perform the subtraction operation on the two null pointers, and the result is still 0.

2.4.2 interaction between the solution reference and pointer arithmetic operations

When an integer value is added to the pointer, the result is still a pointer. You can directly perform the unreference operation on this result, instead of assigning it to a new pointer.

2.4.3 subscript and pointer

Int * p = & ia [2];

Int j = p [1]; // OK, p [1] equivalent to * (p + 1)

// P [1] is the same element as ia [3]

Int k = p [-2]; // OK, p [-2] is the same element as ia [0]

2.4.4 calculate the pointer beyond the end of an array

2.4.5 output array elements

2.4.6 pointer is an array iterator

2.5 pointer and const qualifier

2.5.1 pointer to the const object

If the pointer points to a const object, you cannot use the pointer to change the const value.

Note: you cannot use a pointer to a const object to modify the base object. However, if the pointer points to a non-const object, you can use other methods to modify the object.

2.5.2 const pointer

In addition to the pointer to the const object, the C ++ language also provides the const pointer-its own value cannot be modified.

2.5.3 const pointer to the const object

Const double pi = 3.14159;

Const double * const pi_ptr = & pi;

In this example, you cannot modify the value of the object to which pi_ptr points, or modify the point of the pointer (that is, the address value stored in pi_ptr ).

2.5.4 pointer and typedef

III. C-style string

In fact, the C-style string cannot be exactly attributed to the C language type or the C ++ language type, but is an array of characters ending with null.

3.1.1 use of C-style strings

The C ++ language uses a pointer of the (const) char * type to manipulate a C-style string. In general, we use the arithmetic operation of the pointer to traverse the C-style string. Each time we test the pointer and increment it by 1 until the end character is null.

3.1.2 standard library functions of C-style strings

Standard library functions that manipulate C-style strings
Strlen (s) Returns the length of s, excluding the string Terminator null.
Strcmp (s1, s2) Check whether the two strings s1 and s2 are the same. If s1 is equal to s2, 0 is returned;
If s1 is greater than s2, a positive number is returned. If s1 is smaller than s2, a negative number is returned.
Strcat (s1, s2) Connect string s2 to s1 and return s1
Strcpy (s1, s2) Copy s2 to s1 and return s1
Strncat (s1, s2, n) Connect the first n characters of s2 to the end of s1, and return s1
Strncpy (s1, s2, n) Copy the first n characters of s2 to s1 and return s1

3.1.3 never forget the string Terminator null

3.1.4 The caller must ensure that the target string is of sufficient size.

3.1.5 use the standard library type string whenever possible

3.2 Create a dynamic array

There are three important restrictions on array-type variables: the length of the array is fixed, and the length must be known during compilation. The array only exists in the block statement that defines it.

Each program occupies an available memory space during execution and is used to store dynamically allocated objects. This memory space is called the free storage zone or heap of the program.

3.3 Multi-dimensional array

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.