Home  >  Article  >  Backend Development  >  Definition of two-dimensional array in c++

Definition of two-dimensional array in c++

下次还敢
下次还敢Original
2024-05-07 23:51:19744browse

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.

Definition of two-dimensional array in c++

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is void in c++Next article:What is void in c++