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

Definition of two-dimensional array in c++

下次还敢
Release: 2024-05-07 23:51:19
Original
880 people have browsed it

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>
Copy after login

Example:

<code>int myArray[3][4]; // 创建一个包含 3 行 4 列的二维 int 数组</code>
Copy after login

Element access:

Elements of a two-dimensional array can be accessed through the following syntax:

<code>myArray[行索引][列索引]</code>
Copy after login

Example:

<code>myArray[1][2] = 10; // 将第 2 行第 3 列的值设置为 10
cout << myArray[0][1] << endl; // 输出第 1 行第 2 列的值</code>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
c++
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template