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)

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

  1. Pingback: Computer Science homework Assignment - Custom Elite Writers

  2. Pingback: Computer Science homework Assignment - Academic Writing Company

    • Because in the double for loop that I print the values of the matrix, I append a newline after each element. I could of course modify the code there to have the output in matrix format.

  3. Pingback: SEP:| Online Assignment Writing Service

Leave a reply to anon Cancel reply