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

TheFuzz picture TheFuzz · Nov 20, 2009 · Viewed 59.9k times · Source

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

Answer

Drew Hall picture Drew Hall · Nov 20, 2009

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.