#include<iostream>usingnamespace std;template<typenameT>[[nodiscard]]boolMake1DArray(T*& x,int num){
x =newint[num];if(nullptr!= x){
returntrue;}returnfalse;}template<typenameT>voidDelete1DArray(T*& x){
if(nullptr== x){
return;}delete[] x;
x =nullptr;}template<typenameT>[[nodiscard]]boolMake2DArray(T** x,int rows,int cols){
x =new T*[rows];for(int i =0; i < rows; i++){
x[i]=new T[cols];}returntrue;}template<typenameT>voidDelete2DArray(T** x,int rows){
if(nullptr== x){
return;}for(int i =0; i < rows; i++){
delete[] x[i];}delete[] x;
x =nullptr;}template<typenameT>[[nodiscard]]boolMalloc1DArray(T* x,int num){
x =(T*)malloc(sizeof(T)* num);if(x !=nullptr){
returntrue;}returnfalse;}template<typenameT>voidFree1DArray(T* x){
if(nullptr== x){
return;}free((void*)x);
x =nullptr;}template<typenameT>[[nodiscard]]boolMalloc2DArray(T**& x,int nrow,int nclos){
x =(T**)malloc(sizeof(T*)* nrow);for(int i =0; i < nrow; i++){
x[i]=(T*)malloc(sizeof(T)* nclos);}returntrue;}template<typenameT>voidFree2DArray(T**& x,int nrow){
if(nullptr== x){
return;}for(int i =0; i < nrow;++i){
free((void*)x[i]);}free((void*)x);
x =nullptr;}intmain(){
int n =10;int m =3;
cout <<"new一级指针"<< endl;int* p =nullptr;Make1DArray(p,10);Delete1DArray(p);
cout <<"new二级指针"<< endl;int** q =nullptr;Make2DArray(q, m, n);Delete2DArray(q, n);
cout <<"malloc一级指针"<< endl;int* r =nullptr;Malloc1DArray(r, n);Free1DArray(r);
cout <<"malloc二级指针"<< endl;int** t =nullptr;Malloc2DArray(t, m, n);Free2DArray(t, m);
cout <<"ok"<< endl;/*int **P=new int *[10]; for (int i=0;i<10;++i) { P[i]=new int [10]; } for (int i=0;i<10;++i) { delete []P[i]; }delete []P;*/return0;}
文章评论