C + + Primer Fourth Edition reading notes (iii) arrays and pointers

Source: Internet
Author: User
Tags array definition

The C + + language provides two low-level composite types-arrays and pointers-similar to vector and iterator types. Like the vector type, an array can hold a set of objects of a certain type, but the difference is that the length of the array is fixed. Once an array is created, no new elements are allowed to be added. Pointers can be used like iterators to traverse and examine elements in an array.

Modern C + + programs should use vector and iterator types as much as possible, rather than using low-level arrays and pointers. Well-designed programs use arrays and pointers within the class implementation only when the speed is stressed.

An array is a built-in data structure similar to the standard library vector type in the C + + language. Like vectors, arrays are also a container for storing objects of a single data type, where each object does not have a separate name, but is accessed through its position in the array.

The significant flaw in the array compared to the vector type is that the length of the array is fixed, and the programmer cannot know the length of a given array. The array does not get a size operation for the capacity, nor does it provide an push_back action in which the element is automatically added. If you need to change the length of the array, the programmer can only create a larger new array and then copy all the elements of the original array to the new array space.

One, array

An array is a composite data type consisting of a type name, an identifier, and a dimension that specifies the type of the element that is stored in the array, and the number of elements in the array that is specified by the dimension.

Note: The type name in an array definition can be a built-in data type or a class type, and the type of an array element can be any compound type, except for references. None of the elements are reference arrays.

1.1 Definition and initialization of arrays

The dimensions of an array must be defined with a constant expression with a value greater than or equal to 1. This constant expression can only contain integer literal constants, enumeration constants, or integer const objects initialized with a constant expression. A const variable that is not a const constant and whose value is known to run the stage cannot be used to define the dimensions of the array.

1.1.1 Explicit initialization of array elements

When you define an array, you can provide a comma-delimited set of initial values for its elements, which are enclosed in curly braces {} and become a list of out-of-book words.

If an element's initial value is not explicitly provided, the array element is initialized like a normal variable:

1. A built-in array defined outside the function body, whose elements are initialized to 0;

2, the built-in array defined in the function body, its elements are not initialized;

3, regardless of where the array is defined, if its element is a class type, the default constructor of the class is automatically called for initialization, and if the class does not have a default constructor, you must provide explicit initialization for the array.

Note: The elements of a local array of built-in types are not initialized unless an element's initial value is explicitly provided. At this point, other operations that use these elements are not defined except to assign values to the elements.

1.1.2 Special array of characters

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. Note, however, that the two initialization forms are not identical, and that the string literal contains an extra null character (NULL) for ending the string. When you use string literals to initialize a new array that is created, null characters will be in the new array.

1.1.3 do not allow arrays to be copied and assigned directly

Unlike vectors, an array cannot be initialized with another array, nor can an array be assigned to another array, and these operations are illegal.

1.2 Array Operations

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

1.2.1 Checking array subscript values

As with string and vector types, when using arrays, programmers must also ensure that their subscript values are within the correct range, that is, the array corresponds to an element in that subscript position.

Second, the introduction of pointers

The traversal of a vector can be implemented using subscripts or iterators, and in the same vein, you can use subscripts or pointers to iterate through an array. A pointer is a composite data type that points to an object of a type, and is an iterator for an array: A pointer to an element in the array. Use the dereference operator * and the increment operator + + on a pointer to an array element, similar to the usage on the iterator. You can get the value of the object that the pointer points to by dereferencing the pointer. When the pointer does a self-increment operation, the pointer is moved to point to the next element in the array.

2.1 What is a pointer

The concept of pointers is simple: pointers are used to point to objects. As with iterators, pointers provide indirect access to the objects they refer to, but the pointer structure is more general. Unlike iterators, pointers are used to point to a single object, and iterators can only be used to access elements in the container.

Specifically, the pointer holds the address of another object.

2.2 Definition and initialization of pointers

Each pointer has a data type associated with it that determines the type of object to which the pointer points.

2.2.1 The definition of a pointer variable

String *pstring;

String *p1, *P2, p3;

2.2.2 Another style of declaring pointers

string* PS;

string* P1, p2;

2.2.3 Continuous declaration of multiple pointers easily leads to confusion

In general, defining pointers takes the style: Place the symbol * Close to the pointer variable name.

2.2.4 possible value of the pointer

A valid pointer must be one of the following three states: Save the address of a particular object, point to another object after an object, or 0 value. If the pointer holds a value of 0, it indicates that it does not point to any object. An uninitialized pointer is not valid until the pointer is assigned a value before it can be used.

2.2.5 avoid the use of uninitialized pointers

For most compilers, if an uninitialized pointer is used, the indeterminate value stored in the pointer is treated as an address, and the bit content stored in that memory address is manipulated. Using an uninitialized pointer is equivalent to manipulating the underlying data stored in this indeterminate address. Therefore, when you dereference an uninitialized pointer, it usually causes the program to crash.

2.2.6 constraints for pointer initialization and assignment operations

(1), 0-value constant expression;

(2), the address of the object of type matching;

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

(4), another pointer of the same type.

2.2.7 void* Hands

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

The void* pointer supports only a few limited operations: Comparing with another pointer, passing a void* pointer to a function, or returning a void* pointer from a function, assigning a value to another void* pointer. Using the void* pointer to manipulate the object it points to is not allowed.

2.3 Pointer operation

2.3.1 to generate Lvalue dereference operations

The dereference operator returns the left value of the specified object, which can be used to modify the value of the object that the pointer refers to.

2.3.2 Comparison of pointers and references

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

1. References always point to an object: There are no initialization errors when defining references.

2. Differences in assignment behavior: Modifying a reference assignment is the value of the object that the reference is associated with, rather than associating the reference with another object.

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

2.3.3 Pointer to pointer

2.4 Using pointers to access array elements

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

Arithmetic operation of the 2.4.1 pointer

An arithmetic operation that uses pointers adds (or subtracts) an integer value to a pointer to an element of an array to calculate a pointer value to another element of the array.

In general, adding (or subtracting) an integer value n on the pointer is equivalent to getting a new pointer to the nth element after (or before) the element that the pointer originally pointed to.

Allows the pointer to be added minus 0, leaving the pointer unchanged. More interestingly, if a pointer has a value of 0 (a null pointer), then adding 0 to the pointer is still legal, resulting in another pointer with a value of 0. You can also subtract from two null pointers, and the result is still 0.

2.4.2 interactions between dereference and pointer arithmetic operations

An integer value is added to the pointer, and the result is still a pointer. Allows the dereference to be done directly on this result without first assigning it to a new pointer.

2.4.3 Subscript and pointers

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 an out-of-end pointer to a computed array

2.4.5 Output array elements

2.4.6 Pointer is an iterator to an array

2.5 Pointers and Const qualifiers

2.5.1 pointer to a const object

If the pointer points to a const object, the pointer is not allowed to change the const value that is referred to.

Note: You cannot modify the underlying object with a pointer to a const object, but if the pointer points to a non-const object, other methods can be used to modify the object it refers to.

2.5.2 Const pointer

In addition to pointers to const objects, the C + + language provides a const pointer-the value of itself cannot be modified.

2.5.3 A const pointer to a const object

Const double PI = 3.14159;

Const double *const pi_ptr = π

In this case, you can neither modify the value of the object pointed to by Pi_ptr, nor allow the pointer to be modified (that is, the address value stored in pi_ptr).

2.5.4 Pointers and typedef

Three, C-style strings

In fact, a C-style string cannot be exactly attributed to the C language type, nor to the C + + language type, but to the null-terminated character array.

3.1.1 Use of C-style strings

The C + + language uses a pointer to the (const) char * Type to manipulate the C. style string. In general, we use the arithmetic operations of pointers to traverse the C-style string, testing the pointer each time and incrementing it by 1 until the Terminator is reached null.

3.1.2 Standard library functions for C-style strings

Standard library functions for manipulating C-style strings
Strlen (s) Returns the length of S, excluding the string terminator null
strcmp (S1, S2) Compares two strings of S1 and S2. If S1 and S2 are equal, return 0;
If S1 is greater than S2, returns a positive number, if S1 is less than S2, returns a negative number
strcat (S1, S2) Connects the string S2 to S1 and returns S1
strcpy (S1, S2) Copy the S2 to S1 and return to S1
Strncat (s1, S2, N) Connect prompt the first n characters of S2 to the back of S1 and returns S1
strncpy (s1, S2, N) Copies the first n characters of a s2 to S1 and returns S1

3.1.3 Never forget the string terminator null

3.1.4 Caller must ensure that the target string is of sufficient size

3.1.5 Use standard library type string whenever possible

3.2 Creating dynamic arrays

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

Each program occupies a usable memory space at execution time, which is used to hold dynamically allocated objects, which are called free stores or heaps of programs.

3.3 Multi-dimensional arrays

C + + Primer Fourth Edition reading notes (iii) arrays and pointers

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.