0

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?

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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];
}

2 Comments

@cppgondnler yup, my mistake
How about p[i] = p[i-1] + cols...? :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.