Home > OS >  Use only one column of array as function argument
Use only one column of array as function argument

Time:01-22

Suppose I have a very large array of data:

double matrix[100000][100] = {0.0};

During runtime this data is updated. Now I want to give the reference to this data to a function FUNC. However, I want to only give one column to the function FUNC, like:

FUNC(matrix["all elements"]["only column with index 5"]);

and not the entire array. Furthermore, I dont want to perform a copy operation before (because this is slow), I just want to give the pointer or reference to the specific rows/columns inside the large array data. The function should only see an array like:

void FUNC(double* array)
{
    for (int i = 0; i < 100000; i  )
         doSomething(array[i]);
}

How do I do give this partial data from array "matrix" to the function FUNC?

CodePudding user response:

The column values of your matrix are not sequential in memory, so you can't pass a single column to FUNC() without making a copy of the data into a sequential array. However, if you are able to add the column index as an additional parameter to FUNC() then you can do something like this instead:

const int MAX_ROWS = ...;
const int MAX_COLS = ...;

using Matrix = double[MAX_ROWS][MAX_COLS];

void doSomething(double value)
{
    ...
}

void FUNC(const Matrix& matrix, int column)
{
    for (int row = 0; row < MAX_ROWS;   row) {
         doSomething(matrix[row][column]);
    }
}
Matrix matrix = {};
...
FUNC(matrix, 5);

Online Demo

  • Related