首页 > 解决方案 > Create a contiguous dynamic matrix

问题描述

Arrays have this nice property of being contiguous blocks of memory. When using new to allocate memory for an array, it returns a pointer to a contiguous block of memory. However, if I allocate a matrix using new, like this:

#include <iostream> //std::cin

int main()
{
    int n, m;
    std::cin >> n >> m;
    int** mat = new int*[n];
    for (int i = 0; i < n; i++)
        mat[i] = new int[m];
    //use the matrix in some way
    for (int i = 0; i < n; i++)
        delete[] mat[i];
    delete[] mat;
    return 0;
}

This works, but mat doesn't point to a contiguous block of size n * m * sizeof(int). How can I do this in C++? I am just complying to the latest standard (that is C++17) and nothing else. I want an answer that doesn't involve STL containers or external libraries.

Please don't answer about C, as that is pretty easy to do in both C99 and C11 using variable-length arrays:

#include <stdio.h> //scanf
#include <stdlib.h> //malloc, free

int main()
{
    int n, m;
    scanf("%d %d", &n, &m);
    //int mat[n][m]; VLA, but I want dynamic
    int (*mat)[m] = malloc(n * sizeof *mat);
    //use the matrix in some way;
    free(mat);
    return 0;
}

标签: c++c++17

解决方案


这是您正在做的事情,几乎完全相同,但没有不连续的内存:

#include <iostream> //std::cin
#include <memory>

int main()
{
    int n, m;
    std::cin >> n >> m;
    auto matrix_data = std::make_unique<int[]>(n * m);
    auto mat = std::make_unique<int[]>(n);
    for(int i = 0; i < n; i++) { mat[i] = matrix_data.get() + i * m; }

    // Use the matrix in some way

    // No need to free anything - we're using smart pointers.

    // No need to return 0 from main - that's the default
}

笔记:

  1. 这仍然是丑陋的代码......你可能最好创建一个适当的矩阵类,或者更好 - 使用其他人的实现。
  2. 最好遵循@Someprogrammerdude 的建议并使用算术而不是指针数组。

推荐阅读