创建一维动态数组
- #include <iostream.h>
- main()
- {
- int n1;
- const int DIM1 = 2;
- // 构造数组
- int *ppi = new int[DIM1];
- // 填充数据
- for(n1 = 0; n1 < DIM1; n1++)
- {
- ppi[n1] = n1 ;
- }
- // 输出
- for(n1 = 0; n1 < DIM1; n1++)
- {
- cout << "ppi[" << n1 << "]"
- << ppi[n1] << "/n";
- }
- // 释放数组
- delete [] ppi;
- return 0;
- }
创建二维动态数组
- #include<iostream.h>
- main()
- {
- int n1, n2;
- const int DIM1 = 2;
- const int DIM2 = 3;
- // 构造数组
- int **ppi = new int*[DIM1];
- for(n1 = 0; n1 < DIM1; n1++)
- {
- ppi[n1] = new int[DIM2];
- }
- // 填充数据
- for(n1 = 0; n1 < DIM1; n1++)
- {
- for(n2 = 0; n2 < DIM2; n2++)
- {
- ppi[n1][n2] = 11;
- }
- }
- // 输出
- for(n1 = 0; n1 < DIM1; n1++)
- {
- for(n2 = 0; n2 < DIM2; n2++)
- {
- cout << "ppi[" << n1 << "][" << n2 << "] = "
- << ppi[n1][n2] << "/n";
- }
- }// 释放数组
- for(int n = 0; n1 < DIM1; n1++)
- {
- delete []ppi[n1];
- }
- delete []ppi;
- return 0;
- }
创建三维动态数组
- #include<iostream.h>
- main()
- {
- int n1, n2, n3;
- const int DIM1 = 2;
- const int DIM2 = 3;
- const int DIM3 = 4;
- // 构造数组
- int ***ppi = new int**[DIM1];
- for(n1 = 0; n1 < DIM1; n1++)
- {
- ppi[n1] = new int*[DIM2];
- for(n2 = 0; n2 < DIM2; n2++)
- {
- ppi[n1][n2] = new int[DIM3];
- }
- }
- // 填充数据
- for(n1 = 0; n1 < DIM1; n1++)
- {
- for(n2 = 0; n2 < DIM2; n2++)
- {
- for(n3 = 0; n3 < DIM3; n3++)
- {
- ppi[n1][n2][n3] = n1 * 100 + n2 * 10 + n3;
- }
- }
- }
- // 输出
- for(n1 = 0; n1 < DIM1; n1++)
- {
- for(n2 = 0; n2 < DIM2; n2++)
- {
- for(n3 = 0; n3 < DIM3; n3++)
- {
- cout << "ppi[" << n1 << "][" << n2 << "][" << n3 << "] = "
- << ppi[n1][n2][n3] << "/n";
- }
- }
- }
- // 释放数组
- for(n1 = 0; n1 < DIM1; n1++)
- {
- for(n2 = 0; n2 < DIM2; n2++)
- {
- delete [] ppi[n1][n2];
- }
- delete [] ppi[n1];
- }
- delete [] ppi;
- }
在程序中,动态数组可以很有效的节省存储空间