In C++, I am trying to copy data from one matrix to another. My code is as follows:
int data[height][width];
void MyCode::setData ( int newData[height][width] )
{
for ( int i = 0; i < height; i ++ )
{
for ( int j = 0; j < width; j ++ )
{
data[i][j] = newData[i][j];
}
}
}
My problem here is, these “for” loops are too time consuming, and the code stops just here (maybe the memory is overloaded, I am reading video frames). I wondered about using pointers, like this:
int* data[height][width];
void MyCode::setData ( int* newData[height][width] )
{
data = newData;
}
But it didn’t work, I don’t know the reason. Could someone suggest me a better solution for this?
One way round this is to use a 1D array that is width * height in size. This way you can easily memcpy the data between the two.
Its easy to work out from a row and column what the eventual position in the 1D array is by doing the following:
Edit: If you must use a 2D array then one of the dimensions MUST be known.
As such you can do the following:
In C++ you really are better off using something like a template based solution or such like though as if you pass in an array with the wrong height dimension you will get problems and the compiler will not catch it.
There are plenty of template matrix libraries around. For example:
http://sourceforge.net/projects/tmv-cpp/