如何在VC中创建动态数组
怎樣給多維數(shù)組動(dòng)態(tài)分配內(nèi)存
//Allocate:
int **p = new int* [m];
for(int i = 0 ; i < m ; i++)
p[i] = new int[n];
//Use:
for(int i = 0 ; i < m; i++)
for(int j = 0 ; j < n ; j++)
p[i][j] = i * j;
//Free:
for(int i = 0 ; i < m ; i++)
delete[] p[i];
delete[] p;
1. 演示形為int[2][3]的二維動(dòng)態(tài)數(shù)組
///
int n1, n2;
const int DIM1 = 2;
const int DIM2 = 3;
// 構(gòu)造數(shù)組
int **ppi = new int*[DIM1];
for(n1 = 0; n1 < DIM1; n1++)
{
ppi[n1] = new int[DIM2];
}
// 填充數(shù)據(jù)
for(n1 = 0; n1 < DIM1; n1++)
{
for(n2 = 0; n2 < DIM2; n2++)
{
ppi[n1][n2] = n1 * 10 + n2;
}
}
// 輸出
for(n1 = 0; n1 < DIM1; n1++)
{
for(n2 = 0; n2 < DIM2; n2++)
{
afxDump << "ppi[" << n1 << "][" << n2 << "] = "
<< ppi[n1][n2] << "/n";
}
}
// 釋放數(shù)組
for(n1 = 0; n1 < DIM1; n1++)
{
delete [] ppi[n1];
}
delete [] ppi;
2. 三維動(dòng)態(tài)數(shù)組(int[2][3][4])
///
int n1, n2, n3;
const int DIM1 = 2;
const int DIM2 = 3;
const int DIM3 = 4;
// 構(gòu)造數(shù)組
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];
}
}
// 填充數(shù)據(jù)
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++)
{
afxDump << "ppi[" << n1 << "][" << n2 << "][" << n3 << "] = "
<< ppi[n1][n2][n3] << "/n";
}
}
}
// 釋放數(shù)組
for(n1 = 0; n1 < DIM1; n1++)
{
for(n2 = 0; n2 < DIM2; n2++)
{
delete [] ppi[n1][n2];
}
delete [] ppi[n1];
}
delete [] ppi;
總結(jié)
以上是生活随笔為你收集整理的如何在VC中创建动态数组的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 09 - java 包命名规范
- 下一篇: 惠新宸php教程_百度PHP高级顾问惠新