C++基础:二维数组动态的申请内存和释放内存
使用二维数组的时候,有时候事先并不知道数组的大小,因此就需要动态的申请内存。常见的申请内存的方法有两种:malloc/free 和 new/delete。
一、malloc/free
(1)申请一维数组
void dynamicCreate1Array() { int m; int i; int *p; cout<<("please input the length of data:"); cin >> m; p = (int*)malloc(sizeof(int)*m);//动态开辟 cout << "please input data" << endl; for (i = 0; i < m; i++) cin >> p[i]; cout << "data is :"; for (i = 0; i < m; i++) cout << p[i] << endl; free(p); }
(2)申请二维数组
void dynamicCreate2Array() { int m, n; int i, j; int **p; printf("please input the row and col:"); cin >> m >> n; //scanf("%d%d", &m, &n); p = (int**)malloc(sizeof(int*)*m); //开辟行 for (i = 0; i < m; i++) { *(p + i) = (int*)malloc(sizeof(int)*n);//开辟列 } //输入数据 printf("please input data:"); for (i = 0; i < m; i++) for (j = 0; j < n; j++) cin >> p[i][j]; //输出数据 for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { cout << p[i][j]; } cout << endl; } //释放开辟的二维空间 for (i = 0; i < m; i++) free(*(p + i)); }
二、new/delete
(1)申请一维数组
void DynamicCreate1Array() { int len; int i; cout << "please input the length of data: "; cin >> len; int *p = new int[len]; cout << "please input data: "; for (int i = 0; i < len; i++) cin >> p[i]; cout << "data is " << endl; for (i = 0; i < len; i++) cout <<p[i] << endl; delete[] p; }
(2)申请二维数组
void DynamicCreate2Array() { int m, n; int i; cout << "input row and col: "; cin >> m >> n; //动态开辟空间 int **p = new int*[m]; //开辟行 for (int i = 0; i < m; i++) p[i] = new int[n]; //开辟列 cout << "input data: "; for (i = 0; i < m; i++) for (int j = 0; j < n; j++) cin >> p[i][j]; cout << "output: " << endl; for (i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << p[i][j]<<" "; cout << endl; } //释放开辟的资源 for (i = 0; i < m; i++) delete[] p[i]; delete[] p; }
注:另一种方法:
row:行
col:列
unsigned int **ppPathes;
*ppPathes = (unsigned int *)calloc(row * col, sizeof(unsigned int));
使用malloc:
*ppPathes = (unsigned int *)malloc(sizeof(unsigned int )*(PathNumTemp) * (pathLenTemp + 1));