1. Dynamic two-dimensional array
Objective: to facilitate a configuration matrix of m rows and n columns
2. A simple realization
Here to write a function template
C ++ compiler separation function template is not supported, it is necessary to implement declarations are written in a file
myarray.h:
. 1 #ifndef TESTCPLUS_MYARRAY_H 2 #define TESTCPLUS_MYARRAY_H . 3 . 4 #include <the iostream> . 5 the using namespace STD; . 6 Template <typename T> . 7 / * . 8 functions: malloc space applications partial success, partial failure, the successful recovery portion 9 * / 10 static void freePartMatrix (T ** Pary, int I) . 11 { 12 is for ( int J = I- . 1 ; J> = 0 ; J, ) { 13 is IF (! Pary [J] = nullptr a) { 14 Free(Pary [J]); 15 Pary [J] = nullptr a; 16 } . 17 } 18 is Free (Pary); . 19 } 20 is / * 21 is the function: obtaining a two-dimensional array of m rows and n columns, or a m rows and n columns of the matrix 22 function template 23 is * / 24 template <typename T> 25 T ** getMNMatrix ( int m, int n-) 26 is { 27 IF (m < . 1 || n-< . 1 ) { 28 return nullptr a; 29 } 30 T ** pary = nullptr; 31 pary = (T**)malloc(m*sizeof(T*)); 32 if(pary == nullptr) { 33 return nullptr; 34 } 35 for(int i=0;i<m;++i) { 36 pary[i] = (T*)malloc(n*sizeof(T)); 37 if(pary[i] == nullptr) { 38 freePartMatrix(pary,i); 39 pary = nullptr; 40 return nullptr; 41 } 42 memset(pary[i],0,n*sizeof(T)); 43 } 44 return pary; 45 } 46 47 template <typename T> 48 void print_matrix(T** ary,int m,int n) 49 { 50 if(ary == nullptr) { 51 cout<<"Empty Matrix"<<endl; 52 } 53 for(int i=0;i<m;++i){ 54 for(int j=0;j<n;++j) { 55 cout<<ary[i][j]<<" "; 56 } 57 cout<<"\n"; 58 } 59 } 60 #endif //TESTCPLUS_MYARRAY_H
myarray.cpp
1 #include "myarray.h"
main.cpp
1 int m,n; 2 cin>>m>>n; 3 int** array = getMNMatrix<int>(m,n); 4 print_matrix<int>(array,m,n);