vendredi 3 avril 2020

2d float** or double** array runtime

I have to create an array of array named m2DArray. It has 2 rows and 5 cols i;e a size of [2][5].

The array can be float** or double** which is known to me only at runtime.

Since I do not know the type at compile time, I initialize it in my header files as

void **m2DArray;

Then I create a template function:

template <typename SampleType>
void MyClass::initiliaze2DArray(SampleType** m2DArrayTyped)
{
    m2DArray = m2DArrayTyped;   
    m2DArray = new SampleType* [2]; //2 rows
    int32 sizeOfOneCol =  5 * sizeof(SampleType); // 5 cols
    for (int32 row = 0; row < 2; row++)
    {
        m2DArray[row] = new  SampleType [sizeOfOneColumn];
    memset(m2DArray[row], 0, sizeOfOneCol);
    }
}

Then at runtime I decide between float** or double** based on some logic in the class and accordingly try to initalize the 2d array.

if (somelogictellsfloat){
   float **mArrayFloat;
   initiliaze2DArray(mArrayFloat);
} 
else {
   double **mArrayDouble;
   initiliaze2DArray(mArrayDouble);
}

However, when trying to initialize this 2d array, I am not able to convert the void** to either float** or double** in my template function.

I get the following error:

error: invalid conversion from ‘double**’ to ‘void**’ in line m2DArray = new SampleType* [2];

My Question:

How do I cast **m2DArray from void ** to float ** or double ** ? Or is there a better way to create this 2d array at runtime.

Aucun commentaire:

Enregistrer un commentaire