How to declare dynamic 1D array and use it as 2D array using new in C++

1 Answer

0 votes
#include <iostream>
#include <iomanip>

constexpr int ROW = 3;
constexpr int COL = 4;

int main()
{
    int *matrix = new int[ROW * COL];

    srand(time(NULL));
    for(int i = 0; i < ROW; ++i) {
        for(int j = 0; j < COL; ++j) {
            matrix[j * ROW + i] = rand() % 100;
            std::cout << std::setw(2) << matrix[j * ROW + i] << " ";
        }
        std::cout << "\n";
    }

    delete [] matrix;
 
    return 0;
}
     
     
     
     
/*
run:
   
24 44 18 32 
56 50  1 86 
15 69 84 34
      
*/

 



answered May 12, 2021 by avibootz

Related questions

1 answer 137 views
1 answer 137 views
2 answers 204 views
1 answer 168 views
168 views asked Jan 8, 2017 by avibootz
1 answer 140 views
140 views asked Jan 8, 2017 by avibootz
1 answer 92 views
92 views asked Dec 3, 2024 by avibootz
...