Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate a 2D array of pointers in C++

I'm trying to make a pointer point to a 2D array of pointers. What is the syntax and how would I access elements?

like image 742
TheFuzz Avatar asked Nov 20 '09 04:11

TheFuzz


3 Answers

By the letter of the law, here's how to do it:

// Create 2D array of pointers:
int*** array2d = new (int**)[rows];
for (int i = 0; i < rows; ++i) {
  array2d[i] = new (int*)[cols];
}

// Null out the pointers contained in the array:
for (int i = 0; i < rows; ++i) {
  for (int j = 0; j < cols; ++j) {
    array2d[i][j] = NULL;
  }
}

Be careful to delete the contained pointers, the row arrays, and the column array all separately and in the correct order.

However, more frequently in C++ you'd create a class that internally managed a 1D array of pointers and overload the function call operator to provide 2D indexing. That way you're really have a contiguous array of pointers, rather than an array of arrays of pointers.

like image 142
Drew Hall Avatar answered Sep 21 '22 05:09

Drew Hall


It depends. It can be as simple as:

int main()
{
    int*   data[10][20]; // Fixed size known at compile time

    data[2][3] = new int(4);
}

If you want dynamic sizes at runtime you need to do some work.
But Boost has you covered:

int main()
{
   int  x;
   int  y;
   getWidthAndHeight(x,y);

   // declare a 2D array of int*
   boost::multi_array<int*,2>   data(boost::extents[x][y]);

   data[2][3] = new int(6);
}

If you are fine with jagged arrays that can grow dynamically:

int main()
{
    std::vector<std::vector<int*> >   data;

    data.push_back(std::vector<int*>(10,NULL));
    data[0][3] = new int(7);
}

Note: In all the above. I assume that the array does not own the pointer. Thus it has not been doing any management on the pointers it contains (though for brevity I have been using new int() in the examples). To do memory management correctly you need to do some more work.

like image 44
Martin York Avatar answered Sep 21 '22 05:09

Martin York


int *pointerArray[X][Y];
int **ptrToPointerArray = pointerArray;

That's how you make a true (contiguous in memory) multidimensional array.

But realize that once you cast a multidimensional array to a pointer like that, you lose the ability to index it automatically. You would have to do the multidimensional part of the indexing manually:

int *pointerArray[8][6]; // declare array of pointers
int **ptrToPointerArray = &pointerArray[0][0]; // make a pointer to the array
int *foo = pointerArray[3][1]; // access one element in the array
int *bar = *(ptrToPointerArray + 3*8 + 1); // manually perform row-major indexing for 2d array

foo == bar; // true
int *baz = ptrToPointerArray[3][1]; // syntax error
like image 34
Crashworks Avatar answered Sep 19 '22 05:09

Crashworks