C Primer Plus (10)

Source: Internet
Author: User
Tags float number

Array 10.1

An array is composed of a series of elements of the same type.
The array declaration contains the number and type of array elements.

10.1.1 Initialization

Sometimes you need to use a read-only array, that is, the program reads values from the array, but the program does not write data to the array. In this case, you can use the keyword const during initialization.
Similar to common variables, the value of the array element is not fixed before initialization.
When the number of values is less than the number of array elements, the Redundant Array elements are initialized to 0. If no array is initialized, the array elements are the same as the uninitialized common variables, where useless values are stored;
However, if some arrays are initialized, the uninitialized elements are set to 0.
If the number of items in the initialization list is greater than the array size, the compiler considers this as an error.
You can omit the numbers in parentheses to allow the compiler to automatically match the array size and the number of items in the initialization list.

Because manual computing is prone to errors, computers can calculate the array size. The sizeof operation returns the size of the object or type. Sizeof days is the size of the entire array (in bytes), and sizeof days [0] is the size of an element.

10.1.2 specify the initialization Project (C99)

This feature allows you to initialize certain elements. For example:
Int arr [6] ={ [5] = 212 };
The procedure is as follows:

# Include <stdio. h>
# Define MONTHS 12
Int main (void)
{
Int days [MONTHS] = {31,28, [4] = 31,30, 31, [1] = 29 };
Int index;
For (index = 0; index <MONTHS; index ++)
Printf ("month % 2d has % d days. \ n", index + 1, days [index]);
Return 0;
}

If you initialize an element multiple times, the last time is valid.
When declaring an array, only integer constant expressions can be used in square brackets. The sizeof expression is considered as an integer constant, but a const value is not an integer constant. And the value of this expression must be greater than 0.
C99 introduces a variable-length array to make C more suitable for numerical calculation.

 

10.2 multi-dimensional array

Two-dimensional array declaration method: float rain [5] [12];
Rain is an array containing five elements. The type of each element is float [12]; rain [0] [0] is a float number.
You can also think of rain as a two-dimensional array, which contains five rows and 12 columns in each row. To change the second subscript, you can move along a row, change the first subscript, and move vertically along a column.
Initialize a two-dimensional array, for example, float [5] [12] = {{.....}, {.....}, {.....}, {.....}, {.....}};
Each Value List is enclosed in curly brackets. The first list assigns a value to the first row of the array. During initialization, you can also omit the internal curly braces and only keep the outermost pair of curly braces. As long as the number of values is correct, if not enough, the subsequent elements are initialized to 0.
It is also applicable to 3D arrays.

10.3 pointers and Arrays

Array tag is actually a form of using pointers in disguise. The array name is also the address of the first element of the array. If fizny is an array, finzy = & finzy [0]; both are constants.
The result of adding 1 to A pointer in C is to add one storage unit to the pointer (the size of the byte to which the Pointer Points ). For an array, the address is added to the address of the next element, instead of the next byte.
Finzy + 2 ==& finzy [2]; * (finzy + 2) = finzy [2];
Note that the priority of * (finzy + 2) and * finzy + 2: Indirect operator * is higher than that of +, so the latter is equivalent to: * (finzy) + 2, the former is the value of the third element of the array.
In the function prototype, int * ar can be used to replace int ar [];
When the array name is passed to the function's form parameter, the array size cannot be known. There are two possible solutions.
1. Negotiate a fixed array size in the function code. 2. Pass the array size to the function as the second parameter.

When passing array information to a function, you can pass two pointers, one indicating the starting address of the array and the other specifying the ending address of the array. For example

The end actually points to the position after the last element of the array. C. Make sure that the pointer to the first position after the array is valid when the storage space is allocated to the array.
* Start ++: The unary operator * has the same priority as ++, but it is executed from the right to the left when combined. Although * start ++ is valid, * (start ++) should be used for clarity ).

10.4 pointer operation

The following describes the basic operations that can be performed on Pointer variables:
Value assignment ---- operator * retrieves the value stored in the pointer pointing to the address.
Take the pointer address ---- the pointer variable has the address and value like other variables. Use the operator & to get the address for storing the pointer.
Add an integer to the pointer-the integer is multiplied by the number of bytes indicated by the pointer, and the result is added to the initial address.
Add pointer value ---- you can add a pointer value through the general addition or incremental operator.
Subtract a number from the pointer-the pointer must be the first operand or a pointer to an integer.
Reduce the pointer value ---- the pointer can be reduced.
Evaluate the difference ---- usually evaluate the difference for the pointer pointing to two elements in the same number group to find the distance between elements. The unit of the difference is the size of the corresponding type.
Comparison ---- the premise is that the two pointers have the same type.
C Ensure that the pointer to the array element and the pointer to the first address after the array are valid. However, if the pointer exceeds this range, the consequences are unknown.
You cannot set the value of an uninitialized pointer. This may overwrite program data or code, or even cause program crash.
When creating a pointer, the system only flies with the memory space used to store the pointer itself, and allocates the memory space used to store data.

10.5 protect array content

Because an array is passed to the function, the integrity of the original data may be damaged.
Therefore, you can use the keyword const in the form parameter declaration of function prototype and definition.

10.5.1 other content about const

A pointer to a constant cannot be used to modify a value.
Double rates [5] = {88.99, 100.12, 59.45, 183.11, 340.5 };
Const double * pd = rates;
* Pd = 29.89; // this parameter is not allowed.
Pd [2] = 222.22; // not allowed
Rates [0] = 99.99; // allowed
Pd ++ // allow
Const double locked [4] = {0.08, 0.075, 0.0725, 0.07}; double * pnc; pnc = locked; // The value is invalid.

You can also use two const to create a pointer. This pointer can neither change the pointed address nor modify the pointed data. Const double * const pc = rates;

10.6 pointers and multi-dimensional arrays

Int zippo [4] [2];
The array name zippo is the address of the first element of the array, so the zippo value is the same as & zippo [0. Zippo [0], on the other hand, is an array containing two integers. Therefore, the zippo [0] value is the same as the address of its first element & zippo [0] [0. Zippo [0] is the value of an integer size object, and zippo is the address of two integer size objects. Because the arrays composed of integers and two integers start at the same address, zippo and zippo [0] have the same value.
Adding 1 to A pointer adds a value of the corresponding type to the original value. Therefore, zippo + 1 and zippo [0] + 1 have different results.
* (Zippo [0]) indicates the value of zippo [0] [0], and * zippo indicates the value of zippo [0, that is, & zippo [0] [0]. ** Zippo is equivalent to * & zippo [0] [0], that is, zippo [0] [0].
The equivalent pointer symbol of zippo [2] [1] is represented as * (zippo + 2) + 1 );

10.6.1 pointer to a multi-dimensional array

Int (* pz) [2]; // pz points to an array containing two int values
Int * pz [2]; // create a pointer Array

Int * pt; int ar [3] [2]; int ** pd;
Pd = & pt; // valid. pd is a pointer to a pointer, and pt is a pointer to an int element.
* Pd = ar [0]; // valid. * pd points to a pointer to an element. ar [0] is a pointer to ar [0] [0.
Pd = ar; // invalid

Int * p1;
Const int * p2;
Const int ** pp2;
P1 = p2; // invalid
P2 = p1; // valid
Pp2 = & p1 // illegal
You can also use int sum2 (int ar [3] [4], int rows), but 3 is ignored.
Generally, when declaring a pointer to an n-dimensional array, except the leftmost square brackets can be left blank, all other data needs to be filled.

10.7 variable-length array (VLA)

The C99 standard introduces a variable-length array, which allows variables to be used to define the dimensions of the array. For example
Int quarters = 1;
Int regions = 5;
Double sales [regions] [quarters];
Variable Length array restrictions: VLA must be an automatic storage class, which means they must be declared inside the function or as a function parameter and cannot be initialized during declaration.
Changing does not mean that you can modify the size of an array after it is created. It means that the dimension size can be specified by variables.
Int sum2d (int rows, int cols, int ar [rows] [cols]);
The C99 Standard specifies that the name in the function prototype can be omitted. However, if this parameter is omitted, an asterisk is used to replace the dimension.
Int sum2d (int, int, int ar [*] [*]);

10.8 text

The following is a composite text that creates a nameless array containing two int values:
(Int [2]) {10, 20 };
You can also omit the array size when initializing a composite text.
(Int []) {50, 20, 90 };
Since these compound texts have no names, it is impossible to create them in one statement and then use them in another statement. Instead, you must use them in some way while creating them. One way is to use pointers to save their locations.
Int * pt1;
Pt1 = (int [2]) {10, 20 };

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.