Monday, January 05, 2015

Constant pointer and pointer to a constant, yet another attempt

Master: Appears that 'pointer to a constant' and 'constant pointer' are not understood by so many C++ programmers.

Grasshopper: Ain't that simple, one could not change the value when it is a 'pointer to a constant' while the pointer could not be changed for a 'constant pointer'.

Master: That is what all of them recite like a nursery rhyme, rarely does one tell me what is what.

Grasshopper: Hmm....

Master: Hmm...

Grasshopper: Hmm?

Master: Right, amongst the many attempts around the world the below image is my effort. I really hope this will close the gap that I just noticed.





Grasshopper: I do not think it could be further simplified, I won't ever forget it. Thank you very much.

Master: <Smiles and bows> We could now talk of the differences in them.

Grasshopper: Which become so obvious now...

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;
}