matrix in 2-d dynamic array

Write a program to set up the following matrix in a 2-dimensional array. The array must be dynamic, i.e. must use pointers and the new operator for space allocation.

{11, 12, 13}, // 1st row
{21, 22, 23} // 2nd row
{8, 9, 10} // 3rd row
------------------------------------------------------------

My code so far, please let me know how to set the elements of the array with the for loop.

#include <iostream>
using namespace std;

int main()
{
int **arr = new int*[3];
for (int i = 0; i < 3; ++i)

arr[i] = new int[3];

arr[0][0] = 11;

arr[0][1] = 12;

arr[0][2] = 13;

arr[1][0] = 21;

arr[1][1] = 22;

arr[1][2] = 23;
arr[2][0] = 31;

arr[2][1] = 32;

arr[2][2] = 33;

for(int i = 0; i <= 2; ++i) {
delete [] arr[i];
}
return 0;
}
Last edited on
you may as well hard code it, there is no pattern.

you could do this to save space:
int data[] = {11, 12, 13,21, 22, 23,8, 9, 10};
int dx = 0;
for(all the rows)
for(all the cols)
arr[row][col] = data[dx++];

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>

int main()
{
    const std::size_t N = 3 ;
    // http://en.cppreference.com/w/cpp/language/new
    const auto array = new int [N][N] { {11,12,13}, {21,22,23}, {8,9,10} } ;
    
    for( std::size_t i = 0 ; i < N ; ++i )
    {
        // http://www.stroustrup.com/C++11FAQ.html#for
        for( int v : array[i] ) std::cout << std::setw(3) << v ;
        std::cout << '\n' ;
    }
    
    // http://en.cppreference.com/w/cpp/language/delete    
    delete[] array ;
}

http://coliru.stacked-crooked.com/a/e159883be9cf756b
Topic archived. No new replies allowed.