how to create a global 2d array?

I'm working on a coding problem, and I haven't used C++ in a while.

What I need to do is create a 2d array that I can define outside of the method itself, so it can be referenced by other methods. So what I want to do, in pseudocode, is this:

1
2
3
4
5
6
7
8
class myclass{
  public:
  int* two_d_array

  void test_array(int x, int y){
    two_d_array = new int[x][y]();
  }
}


Is there a way to do this? It seems like I need to define the second dimension of the array, but I need to define it at runtime. Surely there's some way to do this with pointers?

Thanks!
> How to create a global 2d array?

Just create one all you want.

1
2
3
4
5
6
7
8
9
10
int global_array[10000][10000];

class myclass
{
  public:
  int** two_d_array;
  void create_array(int x, int y){
    two_d_array = new int*[x];
    for(int i = 0; i < x; i++) two_d_array[i] = new int[y];
  }
Last edited on
Is this an assignment where you have to use pointers?
If not you better use vectors.
std::vector<vector<int>> globalArray(10, 10);
This would create an 'array' with 10 rows and 10 columns.
Topic archived. No new replies allowed.