1 .定义指针指向二维数组
为了便于根据用户输入动态定义二维数组的行和列,引入变量rowsNum (行)、colsNum (列)列。
在定义5行4列二维数组的示例中,
int rowsNum=4; int colsNum=5; float** a=new float*[rowsNum]; for(intI=0; i rowsNum; I ) {a[i]=new float[colsNum]; }示意图如下。
2.l2释放指针内存
l2指针内存释放与内存申请相似,具体代码如下。
for(intI=0; i rowsNum; I ) { delete[] a[i]; }delete []a;
注意:程序在执行相关功能后,必须释放申请的内存。 程序结束后操作系统会自动清除,但对于需要长时间运行的程序,如果不立即释放内存,程序的运行效率会越来越低,消耗大部分系统内存,也可能影响其他程序的运行。
3 .示例
示例说明如何使用指针指向一维数组,指针指向二维数组。
# includeiostreamusingnamespacestd; voidtest(float**a、float* b、const float* c ) {b[0]=c[0] - 1; b[1]=c[1] - 1; a[0][0]=b[0] c[0]; a[0][1]=b[0] - c[0]; a[0][2]=b[0] * c[0]; a[0][3]=b[0]/c[0]; a[1][0]=b[1] c[1]; a[1][1]=b[1] - c[1]; a[1][2]=b[1] * c[1]; a[1][3]=b[1]/c[1]; (}int main ) ) {int rowsNum=2; int colsNum=4; float** a=new float*[rowsNum]; for(intI=0; i rowsNum; I ) a(I )=newfloat[colsnum]; }float* b=new float[2]; float cbase [2]={ 1.5,1.2 }; float* c=cbase; test(a,b,c ); cout 'a:' endl; for(intI=0; i rowsNum; I ) for(intj=0; j colsNum; j({couta[I][j] '; }cout endl; }cout 'b:' endl; for(intj=0; j 2; j ) {cout b[j] '; }cout endl; cout 'c:' endl; for(intj=0; j 2; {cout c[j] '; }for(intI=0; i rowsNum; I ) { delete[] a[i]; }delete []a; delete []b; 返回0; }