Home >Backend Development >C#.Net Tutorial >How to represent two-dimensional array in c language

How to represent two-dimensional array in c language

下次还敢
下次还敢Original
2024-05-02 19:06:44586browse

Two-dimensional arrays store table-like data and are declared as the data type of arrays in C language. Initialization methods include: 1) element-by-element initialization; 2) row-level initialization; 3) using pointers. Element access is via row and column index.

How to represent two-dimensional array in c language

Representation of two-dimensional array in C language

Two-dimensional array is used to represent a two-dimensional array with row and column dimensions Table-like data structure. In C language, a two-dimensional array is declared as a data type whose data type is array.

Declare a two-dimensional array

Syntax:

<code class="c">数据类型 数组名[行数][列数];</code>

For example:

<code class="c">int matrix[3][4];</code>

This will declare an array named matrix is a two-dimensional array of integers with 3 rows and 4 columns.

Initializing a two-dimensional array

A two-dimensional array can be initialized in three ways:

  • Element-by-element initialization:
<code class="c">int matrix[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};</code>
  • Row-level initialization:
<code class="c">int matrix[3][4] = {
    [0] = {1, 2, 3, 4},
    [1] = {5, 6, 7, 8},
    [2] = {9, 10, 11, 12}
};</code>
  • Using pointers:
<code class="c">int *matrix = (int *)malloc(3 * 4 * sizeof(int));</code>

Accessing elements in a two-dimensional array

You can use row and column index to access elements in a two-dimensional array:

<code class="c">matrix[行号][列号];</code>

For example:

<code class="c">printf("%d", matrix[1][2]);  // 输出 7</code>

Memory representation

In memory, a two-dimensional array is stored as a contiguous block of elements. Rows are stored in adjacent memory locations, and columns are stored in adjacent locations to the rows.

The above is the detailed content of How to represent two-dimensional array in c language. 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