Home >Backend Development >C++ >How to define a two-dimensional array in c++
How to define a two-dimensional array in C: declare the array type: int arr row number; use nested loops to initialize the array elements; use the subscript operator to access the array elements.
Define a two-dimensional array in C
In C, a two-dimensional array is a data structure, using Used to store data organized in rows and columns. To define a two-dimensional array, use the following steps:
Declare the array type
<code class="cpp">int arr[行数][列数];</code>
where:
arr
is the name of the array. Number of rows
and Number of columns
Specify the number of rows and columns of the array. For example:
<code class="cpp">int matrix[3][4]; // 声明一个 3 行 4 列的整数数组</code>
Initializing the array
After declaring an array, you can use a nested loop to initialize it element.
For example:
<code class="cpp">for (int i = 0; i < 3; i++) { // 遍历行 for (int j = 0; j < 4; j++) { // 遍历列 matrix[i][j] = i * j; // 初始化元素 } }</code>
To access array elements
you can use the subscript operator[]
Access array elements.
For example:
<code class="cpp">int element = matrix[1][2]; // 获取第 2 行第 3 列的元素(索引从 0 开始)</code>
Note:
The above is the detailed content of How to define a two-dimensional array in c++. For more information, please follow other related articles on the PHP Chinese website!