Search code examples
c++arraysmultidimensional-arraynew-operator

Dynamic Multidimensional Array in C++


The program should take a dimension n and make a multidimensional array of nxn dimensions, I know it has to be done with the new[ ] operator, thus it should be done using pointers, I found a lot of ways on the internet but I´m new to this topic and couldn't understand well how they work, here is one of those codes I found that claims to work:

main()
{
    double n;
    cout<<"Enter the n dimension to the matrix[nxn]: ";
    cin>>n;
    matrix=new int*[n];
    int *data=new int[n*n];
    for(i=0;i<n;i++)
      matrix[i]=&data[i*n];
}

My question is: is this code right? if so, how does it work? otherwise, which code does work? (if you could and a little explanation I'd appreciate it)


Solution

  • You should not use raw pointers, better use std::vector.

    #include <iostream>
    #include <vector>
    
    int main() {
        int n;
        std::cin << n;
    
        std::vector<std::vector<int>> matrix(n, std::vector<int>(n));
        // Do whatever with matrix
    
        return 0;
    }