> For the complete documentation index, see [llms.txt](https://op-al.gitbook.io/s-30-voprosy-i-dop.-voprosy/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://op-al.gitbook.io/s-30-voprosy-i-dop.-voprosy/13.-organizaciya-dvumernykh-massivov-matric-.-staticheskoe-i-dinamicheskoe-vydelenie-pamyati-pod-mat.md).

# 13.	Организация двумерных массивов (матриц). Статическое и динамическое выделение памяти под матрицу

**Двумерный массив** - это массив одномерных массивов. В одномерном массиве положение элемента определяется одним индексом, а в двумерном — двумя.

### Статическое выделение памяти <a href="#staticheskoe-vydelenie-pamyati" id="staticheskoe-vydelenie-pamyati"></a>

`float mat[4][4];` - создание матрицы 4x4. Первое число - строки, второе - столбцы

### Динамическое выделение памяти: <a href="#dinamicheskoe-vydelenie-pamyati" id="dinamicheskoe-vydelenie-pamyati"></a>

1. Линейный способ. (Все элементы матрицы будут располагаться друг за другом: сначала все элементы 0 строки, затем все элементы первой и т.д.)

```c
void* alloc_memory_matrix (int row, int col, size_t element_size){
    return malloc(row * col* element_size);
}
```

2. Стандартный способ выделения памяти.

```c
double** alloc_memory_matrix(int row, int col)
{
    double **mat = (double**) malloc(row * sizeof(double*));
    if (mat != NULL) {
        for (int i = 0; i < row; i++) {
            *(mat + i) = (double*) malloc(col *sizeof(double));
            if (*(mat + i) == NULL) {
                while (--i >= 0)
                    free (*(mat + i));
                free(mat);
                mat = NULL;
                break;
            }
        }
    }
    return mat;
}
```

3. Способ выделения памяти единым блоком с сохранением указателей на строки

При таком способе выделения памяти, память сразу же выделяется под указатели на строки и под каждый элемент в частности. Далее устанавливается соответствие между указателем на строку и первым элементом строки.

```c
double** alloc_memory_matrix(int row, int col)
{
    double** mat = (double**) malloc(row * sizeof(double*) + row * col * sizeof(double));
    double *mat_body = (double*)(mat + row);
    for (int i = 0; i < row; i++){
        *(mat + i) = mat_body + i * col;
    }
    return mat;
}
```

### Передача двумерных массивов в функции <a href="#peredacha-dvumernykh-massivov-v-funkcii" id="peredacha-dvumernykh-massivov-v-funkcii"></a>

`int fun(int array[n][m])`

`int fun(int *array[m])`

`int fun(int **array)`


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://op-al.gitbook.io/s-30-voprosy-i-dop.-voprosy/13.-organizaciya-dvumernykh-massivov-matric-.-staticheskoe-i-dinamicheskoe-vydelenie-pamyati-pod-mat.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
