Arrays
An array is a container that stores objects of the same type. The objects stored in an array do not have names; instead, they are accessed by their positions. The size of an array is fixed; the length of an array cannot be changed arbitrarily.
Defining Arrays
An array is declared as a[d], where a is the name of the array and d is the number of elements in the array. At compile time, d must be known, meaning d should be an integer constant expression.
1 2 3 4 | |
You cannot directly assign one array to another:
1 2 3 | |
It is advisable to define larger arrays as global variables. Local variables are created on the stack, and excessively large arrays (larger than the stack size) can cause a stack overflow, leading to a runtime error (RE). If an array is declared in the global scope, it will be created in the static area.
Accessing Array Elements
Array elements can be accessed using the subscript operator []. Array indices (the values inside the square brackets) start from 0. For example, an array with 10 elements has indices from 0 to 9, not 1 to 10. However, in competitive programming, for convenience, we often allocate arrays slightly larger and start accessing elements from index 1, ignoring the first element.
Example 1: Read an integer \(n\) from standard input, then read \(n\) numbers and store them in an array. Here, \(n \leq 1000\).
1 2 3 4 5 6 7 8 9 10 11 12 | |
Example 2: (Continuing from Example 1) Sum the elements in array arr and output the sum. It is guaranteed that the sum of all elements in the array is less than or equal to \(2^{31} - 1\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
Out-of-Bounds Access
The array index \(\mathit{idx}\) should satisfy \(0 \leq \mathit{idx} < \mathit{size}\). If the index is outside this range, it results in undefined behavior, which can lead to unpredictable consequences such as segmentation faults or unintended modifications of other variables.
Multidimensional Arrays
A multidimensional array is essentially an "array of arrays," meaning the elements of the outer array are themselves arrays. A two-dimensional array requires two dimensions to define: the length of the array and the length of its elements. Accessing a two-dimensional array requires two indices:
1 2 | |
We often use nested for loops to process two-dimensional arrays.
Example: Read two numbers \(n\) and \(m\) from standard input, representing the height and width of a black-and-white image, respectively, with \(n, m \leq 1000\). For the next \(n\) lines of data, each line contains \(m\) space-separated numbers representing the brightness values at each position. Now, read this image and store it in a two-dimensional array.
1 2 3 4 5 6 7 | |
Similarly, you can define three-dimensional, four-dimensional, and even higher-dimensional arrays.
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用