When we define a two-dimensional pointer, if we need to store the corresponding data, we need to dynamically allocate memory, at this time, there is a need to pay attention to, the allocation of memory is different, the continuity of memory is not the same, first of all, bloggers first posted the test code:
#include <cstdlib> #include <iostream> using namespace std;
#define NWIDTH 3 #define NHEIGHT 4//memory continuous distribution problem int main (int argc, char *argv[]) {int **p = NULL;
p = (int**) malloc (nwidth*sizeof (int*));
if (p = = NULL) return-1;
cout<< "Non-Continuous memory allocation:" <<endl;
for (int j = 0; j< nwidth + +) {P[j] = (int*) malloc (nheight*sizeof (int));
if (p[j] = = NULL) return-1;
for (int i = 0; i < nwidth. i++) for (int j = 0; J < nheight; J +) {
printf ("%p", &p[i][j]);
if (j = = nHeight-1) cout<<endl;
} cout<<endl;
for (int j = 0; J < nwidth; J + +) {free (p[j]);
P[J] = NULL;
Free (p);
p = NULL;
int **q = NULL; Q = (int**) malloc (nwidth*sizeof (int*));
if (q = = NULL) return-1;
cout<< "Continuous memory allocation:" <<endl;
Q[0] = (int*) malloc (nwidth*nheight*sizeof (int));
if (q[0] = = NULL) {free (q);
return-1;
for (int i = 1;i < nwidth; i++) q[i] = q[i-1] + nheight; for (int i = 0; i < nwidth i++) for (int j = 0; J < nheight; J +) {printf ("%p", &
AMP;Q[I][J]);
if (j = = nHeight-1) cout<<endl;
} cout<<endl;
Free (q[0]);
Q[0] = NULL;
Free (q);
Q = NULL;
System ("PAUSE");
return exit_success; }