1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
const std::size_t N = 3 ;
template < typename ARR_NxN > void print( const ARR_NxN& array ) ;
int main()
{
{
// this is the sane thing to do; we don't need dynamic storage duration
int values[N][N] = { {1,2,3}, {4,5,6}, {7,8,9} } ;
print(values) ;
}
{
// dynamically allocated 2d array. ideally, use std::unique_ptr<int[]>
auto values = new int[N][N] { {1,2,3}, {4,5,6}, {7,8,9} } ;
print(values) ;
delete[] values ;
}
{
// dynamically allocated array of pointers (as in the code in the earlier posts),
// with each pointer pointing to the first element of a dynamically allocated array
// bad: not exception safe (also as in the code in the earlier posts)
auto values = new int* [N] { new int[N]{1,2,3}, new int[N]{4,5,6}, new int[N]{7,8,9} } ;
print(values) ;
for( std::size_t i = 0 ; i < N ; ++i ) delete[] values[i] ;
delete[] values ;
}
}
template < typename ARR_NxN > void print( const ARR_NxN& array )
{
for( std::size_t row = 0 ; row < N ; ++row )
{
for( std::size_t col = 0 ; col < N ; ++col ) std::cout << array[row][col] << ' ' ;
std::cout << '\n' ;
}
std::cout << "------\n" ;
}
| |