多维数组的动态分配(二三维)
本文主要目的是用c和c++分别实现动态分配二、三维数组。一般而言,在C中用malloc和free实现,而在C++中用new和delete。 new和delete是c++操作符,malloc和free是c语言函数,它们都可以用来为对象动态分配空间,最大的区别在于:当用new和 delete为对象分配空间或delete对象时,将缺省的调用对象的构造函数及析购函数,而malloc和free是原来c库中的函数,显然没有这项功 能,因此,在c++中,最好使用new和delete。
//c用malloc和free//
#i nclude "stdio.h"
#i nclude "stdlib.h"
void main()
{
int **p;
int i,j; //p[4][8]
//开始分配4行8列的二维数据
p = (int**)malloc(sizeof(int*)*4);
for(i=0; i<4; i++)
p[i] = (int*)malloc(sizeof(int)*8);
for(i=0; i<4; i++)
for(j=0; j<8; j++)
p[i][j] = j*i;
//打印数据
for(i=0; i<4; i++)
for(j=0; j<8; j++)
{
if(j==0) printf("\n");
printf("%3d",p[i][j]);
}
//开始释放申请的堆
for(i=0; i<4; i++)
free(p[i]);
free(p);
}
///
//c++用new和delete/
#i nclude <iostream>
using namespace std;
void main()
{
int **p;
int i,j; //p[4][8]
//开始分配4行8列的二维数据
p = new int *[4];
for(i=0;i<4;i++)
p[i]=new int [8];
for(i=0; i<4; i++)
for(j=0; j<8; j++)
p[i][j] = j*i;
//打印数据
for(i=0; i<4; i++)
for(j=0; j<8; j++)
{
if(j==0) cout<<endl;
cout<<p[i][j]<<"\t";
}
//开始释放申请的堆
for(i=0; i<4; i++)
delete [] p[i];
delete [] p;
}
///
动态分配三维数组的程序
//c用malloc和free//
#i nclude "stdlib.h"
#i nclude "stdio.h"
void main()
{
int i,j,k; //p[2][3][4]
char ***p = (char***)malloc(2* sizeof(char**));
for(i=0; i<2; i++)
{
p[i] = (char**)malloc(3*sizeof(char*));
for(j=0; j<3; j++)
{
p[i][j] = (char*)malloc(4*sizeof(char));
}
}
//finish creating use p[i][j][k] to access the data
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
for(k=0;k<4;k++)
{
p[i][j][k]=i+j+k;
printf("%d ",p[i][j][k]);
}
printf("\n");
}
printf("\n");
}
//free the memory
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
free(p[i][j]);
}
}
for(i=0; i<2; i++)
{
free(p[i]);
}
free(p);
}
///
//c++用new和delete/
#i nclude <iostream>
using namespace std;
void main()
{
int i,j,k; // p[2][3][4]
int ***p;
p = new int **[2];
for(i=0; i<2; i++)
{
p[i]=new int *[3];
for(j=0; j<3; j++)
p[i][j]=new int[4];
}
//finish creating use p[i][j][k] to access the data
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
for(k=0;k<4;k++)
{
p[i][j][k]=i+j+k;
cout<<p[i][j][k]<<" ";
}
cout<<endl;
}
cout<<endl;
}
//free the memory
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
delete [] p[i][j];
}
}
for(i=0; i<2; i++)
{
delete [] p[i];
}
delete [] p;
}