Sunday, January 04, 2015

Dynamically assign memory to 2D array of integers

Understanding memory management is critical for C++ programmers. One of my colleagues asks people to write code to assign memory to 2D array of integers. The below program shows an easy way of doing that.


#include <iostream>

typedef int* IntPtr;

int main()
{
const int numCols = 5;
const int numRows = 20;

// assign memory for rows
IntPtr* intPtrArr = new IntPtr[numRows];

// now assign memory for columns in each row
for (int i = 0; i < numRows; i++)
{
intPtrArr[i] = new int[numCols];
}

// now assign values to each element
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
intPtrArr[i][j] = (i + 1)*(j + 1);
}
}

// now print whatever is in the array
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
std::cout << intPtrArr[i][j] << " ";
}
std::cout << std::endl;
}

return 0;
}



No comments: