Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to dynamically allocate a 2D std::array in C++ or why I should not use it?

I want to malloc an array in my code, and its size should be defined at runtime.

I tried like this:

#include <iostream>
#include <array>

int main(){
    int M=4,N=3,P=5;
    M=N+P;
    std::array<std::array<double,M>,N> arr;
}

But MSVC told me:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a variable with non-static storage duration cannot be used as a non-type argument

I don’t find the answer to this in stackoverflow.(The existing question seem not to solve my problem…)

How to dynamically allocate a 2D std::array in C++?

I know I could use std::vector to solve this. But the vector memory size needs to be organized by myself and this would be used many times in my project. And I want to use C++ type code rather than C type…Maybe there is a method to turn a 2D array in C type to std::array, but I can’t find it by Google…

So I ask this question…

I mean the M and N should be got dynamically(not changed,but I can only know it in runtime…),like:

#include <iostream>

int main(){
    int a=3;
    int b=4;
    int rowCount=a+b;
    int colCout=b-a;
    int** a = new int*[rowCount];
    for(int i = 0; i < rowCount; ++i)
    {
        a[i] = new int[colCount];
    }
}

I know where is my mistake. I fell into a logical question… If I don’t use push_back,the vector works well. If I use it, the array doesn’t work, too.

>Solution :

The dynamically allocated array container in C++ is std::vector. std::array is for specifically compile-time fixed-length arrays.

https://cppreference.com is your friend!

But the vector memory size needs to be organized by myself

Not quite sure what you mean with that, but you specify the size of your std::vector using the constructor.

std::vector<std::vector<int>> arr(N);

If you need some special allocator (not just new/malloc), then you can also specify a custom allocator.

Your whole program that you propose is not good C++. A C++ solution would look like:

#include <vector>
int main() {
    int a = 3;
    int b = 4;
    unsigned int rowCount = a + b;
    unsigned int colCount = b - a;
    std::vector<std::vector<int>> matrix(rowCount);
    for (auto& row : matrix) {
        row.resize(colCount);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading