dynamic 2D array in C++

2Darray.cpp

A 2D array is basically a 1D array of pointers, where every pointer is pointing to a 1D array, which will hold the actual data.

#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

Relevant answer in Stackoverflow.

Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

6 thoughts on “dynamic 2D array in C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s