多维数组的动态开辟与释放:
C方式:
#include <stdio.h>
#include <assert.h>
#define ROW 3
#define COL 4
void main()
{
int i = 0;
int j = 0;
//申请空间
int **p = (int **)malloc(sizeof(int*)*ROW);
assert(p != NULL);
for(i = 0; i < ROW; ++i){
p[i] = (int *)malloc(sizeof(int)*COL);
assert(p[i] != NULL);
}
//赋值
for(i = 0; i < ROW; ++i){
for(j = 0; j < COL; ++j){
p[i][j] = i + j;
}
}
//显示
for(i = 0; i < ROW; ++i){
for(j = 0; j < COL; ++j){
printf("%d ",p[i][j]);
}
printf("\n");
}
//释放空间
for(i = 0; i < ROW; ++i){
free(p[i]);
}
free(p);
}
C++方式:
#include <iostream>
#include <assert.h>
using namespace std;
const int row = 3;
const int col = 4;
void main()
{
//申请空间
int **p = new int*[row];
assert(p != NULL);
for(int i = 0; i < row; ++i){
p[i] = new int[col];
assert(p[i] != NULL);
}
//赋值
for(i = 0; i < ROW; ++i){
for(int j = 0; j < COL; ++j){
p[i][j] = i + j;
}
}
//显示
for(i = 0; i < ROW; ++i){
for(j = 0; j < COL; ++j){
cout<<p[i][j];
}
cout<<endl;
}
//释放
for(i = 0; i < row; ++i){
delete []p[i];
}
delete []p;
}