熟悉下new,delete, malloc, free。
不过好像混用也可以
不过好像混用也可以
- #include <stdlib.h>
- #include <assert.h>
- #include <iostream>
- using namespace std;
- template<class T>
- bool Make2DArray(T** &x, int rows, int cols)
- {
- try{
- x = new T*[rows];
- for (int i=0; i<rows; i++)
- x[i] = new T[cols];
- return true;
- }catch(...)
- {
- cerr<<"new error!"<<endl;
- return false;
- }
- }
- template<class T>
- void Delete2DArray(T **&x, int rows)
- {
- for (int i=0; i<rows; i++)
- {
- delete[] x[i];
- }
- delete[] x;
- x = NULL;
- }
- bool Make(char **&x, int rows, int cols)
- {
- int i;
- x = (char **)malloc(sizeof(char *)*rows);
- assert(x != NULL);
- for (i=0; i<cols; i++)
- {
- x[i] = (char *)malloc(sizeof(char)*cols);
- assert(x[i]);
- }
- return true;
- }
- void free2D(char **&p, int rows)
- {
- int i;
- for (i=0; i<rows; i++)
- {
- free(p[i]);
- p[i] = NULL;
- }
- free(p);
- p = NULL;
- }