C++ to allocate memory to the two dimensional pointer of of implementation code
- 2020-04-02 01:56:03
- OfStack
The principle is not written here, after all, there are a lot of online introduction, the code is as follows:
#include <iostream>
using namespace std;
#define N 5
#define M 10
int main(int argc, char **argv)
{
int **p;
int i,j;
p = new int* [N];
for (i = 0; i < N; i++)
p[i] = new int [M];
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
p[i][j] = i + j;
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
{
cout<<"["<<p[i][j]<<"]"<<" ";
cout<<*(*(p + i) + j)<<" "<<endl;
}
cout<<endl;
}
for (i = 0; i < N; i++)
{
delete [] p[i];
p[i] = NULL;
}
delete [] p;
p = NULL;
return 0;
}