what is this the correct way to pass 2 dimensional array of unknown size?
reprVectorsTree::reprVectorsTree(float tree[][], int noOfVectors, int dimensions)
<
If the size is unknown, you can use a simple float *tree
pointer to a 1D array. The syntax for turning to particular elements wouldn't be as of 2D arrays however:
reprVectorsTree::reprVectorsTree(float *tree, int noOfVectors, int dimensions)
{
...
tree[ row_number * dimensions + column_number ] = 100.234;
}
In the calling code you will have something like this:
float d2array[ROWS][COLUMNS];
...
reprVectorsTree(&d2array[0][0], ROWS, COLUMNS);
updated
Consider the following example of different approaches of passing a 2D array:
#include
#include
float test[2][4] =
{
{3.0, 4.0, 5.0, 0},
{6.0, 7.0, 8.0, 0}
};
void print(float *root, int rows, int columns)
{
for (int row = 0; row < rows; ++row)
{
for (int col = 0; col < columns; ++col)
{
std::cout << root[row * columns + col ] << " ";
}
std::cout << std::endl;
}
}
float *test2[2] =
{
&test[0][0],
&test[1][0],
};
void print2(float **root, int rows, int columns)
{
for (int row = 0; row < rows; ++row)
{
for (int col = 0; col < columns; ++col)
{
std::cout << root[row][col] << " ";
}
std::cout << std::endl;
}
}
int main()
{
print(&test[0][0], 2, 4);
//print(test2, 2, 4); // doesn't work
print2(test2, 2, 4);
//print2(&test[0][0], 2, 4); // doesn't work
//print2(&test[0], 2, 4); // doesn't work
float **dynamic_array = (float **)malloc(2 * sizeof(float *));
dynamic_array[0] = (float *)malloc(4 * sizeof(float));
dynamic_array[1] = (float *)malloc(4 * sizeof(float));
for (int row = 0; row < 2; ++row)
{
for (int col = 0; col < 4; ++col)
{
dynamic_array[row][col] = (float)(row * 4 + col);
}
}
print2(dynamic_array, 2, 4);
//print(dynamic_array, 2, 4); // doesn't work
return 0;
}