Implementation of C and C++ dynamic allocation of two dimensional array
- 2020-05-10 18:33:42
- OfStack
C:
The functions malloc and free are used in C.
// Dynamic allocation M*N d
int **a=(int **)malloc(sizeof(int*)*M);
for(int i=0;i<M;i++)
a[i]=(int *)malloc(sizeof(int)*N);
// The dynamic release
for(int j=0;j<M;j++)
free(a[i]);
free[a];
C + + :
C++ USES the keywords new and delete.
// Dynamic allocation M*N d
int **a=new int *[M];
for(int i=0;i<M;i++)
a[i]=new int[N];
// The dynamic release
for(int j=0;j<M;j++)
delete[] a[i];
delete[] a;