Home > Article > Backend Development > Definition of two-dimensional array in c++
In C, the definition format of a two-dimensional array is: data type array name row number. Elements are accessed via row index. Can be initialized via nested braces or dynamic allocation. Memory needs to be released after dynamic allocation to avoid leaks.
Two-dimensional array definition in C
Definition format:
<code>数据类型 数组名[行数][列数];</code>
Example:
<code>int myArray[3][4]; // 创建一个包含 3 行 4 列的二维 int 数组</code>
Element access:
Elements of a two-dimensional array can be accessed through the following syntax:
<code>myArray[行索引][列索引]</code>
Example:
<code>myArray[1][2] = 10; // 将第 2 行第 3 列的值设置为 10 cout << myArray[0][1] << endl; // 输出第 1 行第 2 列的值</code>
Initialization:
Two-dimensional arrays can be initialized when defined, using nested braces:
<code>int myArray[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };</code>
Dynamic allocation:
You can also use pointers to dynamically allocate two-dimensional arrays:
<code>int **myArray = new int*[行数]; for (int i = 0; i < 行数; i++) { myArray[i] = new int[列数]; }</code>
Release memory:
Dynamic The allocated 2D array needs to free the memory to avoid memory leaks:
<code>for (int i = 0; i < 行数; i++) { delete[] myArray[i]; } delete[] myArray;</code>
The above is the detailed content of Definition of two-dimensional array in c++. For more information, please follow other related articles on the PHP Chinese website!