# C++二維指標動態分配記憶體連續問題

`#include <cstdlib>  #include <iostream>        using namespace std;        #define nWidth  3  #define nHeight 4        //記憶體是否連續分配問題   int main(int argc, char *argv[])  {      int **p = NULL;      p = (int**)malloc(nWidth*sizeof(int*));      if(p == NULL)      return -1;                cout<<"記憶體的不連續分配："<<endl;      for(int j = 0; j< nWidth; j++)      {         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<<"記憶體的連續分配："<<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  ",&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;  }`

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD