简体   繁体   中英

C++ Pointer to 2D Dynamic Array?

I am a bit of a C++ newbie and I am working on a project and I a little stuck. I need to create a dynamic 2D ragged array then have a pointer point to it. Here is what I have:

int ** x = new int*[3];
int *** y = ???;

Now, after I do:

x[n] = new int[length];
x[++n] = new int[length2];
//etc etc

I can access the values in the array through a statement like:

int num = x[i][j];

What I want is to be able to the same array values through y like:

int num2 = *y[i][j];

So, in this case, num2 and num should have the same value, how would I go about allocating the memory for y and assigning it?

Thanks!

A pointer to x would be:

int *** y = &x;

There is no need to allocate space for y.

Here is an example of creating a 2D array in C++.

#include <iostream>

int main() {
  // dimensions
  int N = 3;
  int M = 3;

  // dynamic allocation
  int** ary = new int*[N];
  for(int i = 0; i < N; ++i)
      ary[i] = new int[M];

  // fill
  for(int i = 0; i < N; ++i)
    for(int j = 0; j < M; ++j)
      ary[i][j] = i;

  // print
  for(int i = 0; i < N; ++i)
    for(int j = 0; j < M; ++j)
      std::cout << ary[i][j] << "\n";

  // free
  for(int i = 0; i < N; ++i)
    delete(ary[i]);
  delete [] ary;

  return 0;
}

// OUTPUT
0
0
0
1
1
1
2
2
2

Check this answer too for more.

So now, you have created the 2D array. You want just a pointer to point to it. You do not need to allocate memory again (this would be wrong)!

So, you just need to do something like this:

  int ***p = &ary;

  // print
  for(int i = 0; i < N; ++i)
    for(int j = 0; j < M; ++j)
      std::cout << (*p)[i][j] << "\n";

...but wait, it's C++! You should use std::array or std::vector instead of primitive arrays (expanding them for 2D, like std::vector< std::vector >)!

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