简体   繁体   中英

Declaring contiguous 2D array pointer

I have learnt to declare a dynamic 2D array using a pointer as such. However I was told this does not create a contiguous 2D array.

int **p;
p = new int*[M];
for (int i = 0; i < M; ++i) {
    p[i] = new int[N]; }

What is the way to modify the code to create a dynamic pointer to a contiguous 2D array?

For a continuous 2D array create a buffer with size MxN and access it using y*M+x:

const int M=10, N=5;
int *p = new int[M*N];
  for (int y = 0; y < N; ++y)
    for (int x = 0; x < M; ++x)
      p[y*M+x] = y*M+x;
      
for (int x = 0; x < M*N; ++x)
      std::cout << p[x] << std::endl; 

Have a try with this

int **p= new int*[rows];
int size= rows*cols;
p[0]= new int[size];
for(int i= 1; i < rows; i++) {
    p[i]= &p[0][i*cols];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM