Purnendu Kumar
Purnendu Kumar

Reputation: 41

Passing three dimensional array by reference in c++

Function is defined as:

int strip(double *signalstnV){
.
.
return 0;
}

And main function it is called as:

main{
.
.
double signalstnV[iteration][2*range+1][3];
.
.
check = strip(signalstnV);
.
}

I wanted to use the array in next function in main after it is modified in strip function. But during compilation i am getting an error as following

sim.C: In function ‘int main(int, char**)’:

sim.C:54:26: error: cannot convert ‘double ()[151][3]’ to ‘double’ for argument ‘1’ to ‘int strip(double*)’

check = strip(signalstnV);

I am not able to understand it. Please help. My main goal is to generate array from strip function and pass it to other functions later in code.

Also when i used this array in another function

threshold(double * signalstnV)

and using a for loop to extract some specific values, it gives error as:

invalid types ‘double[int]’ for array subscript 
if (signalstnV[k][j][3] < -0.015){
..}

Upvotes: 4

Views: 1825

Answers (3)

PiotrNycz
PiotrNycz

Reputation: 24430

For such cases, with more or less complicated types - use type aliases:

//double signalstnV[iteration][2*range+1][3];
using IterationValues = double[iteration];
using IterationRangesValues = IterationValues [2*range+1];
//...

then, it is obvious that calling this:

IterationRangesValues signalstnV[3];
check = strip(signalstnV);

You need this signature: strip(IterationRangesValues * matrix) or this strip(IterationRangesValues (& matrix)[3]). Of course for this last array you might use typedef too.

You might also use std::array:

using IterationValues = std::array<double, iteration>;
using IterationRangesValues = std::array<IterationValues, 2*range+1>;
//...

Upvotes: 2

M.M
M.M

Reputation: 141658

To pass the array by reference, one way is:

template<size_t X, size_t Y, size_t Z>
int strip( double(&strip)[X][Y][Z] )
{
}

Then you can call it with various sizes of array.

If you only need to support the one size, then remove the template line and replace X Y Z with the actual dimensions you need to support.

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

An ordinary single-dimensional array decays to a pointer to its first value. A multi-dimensional array decays only in its first dimension, decaying to a pointer to the initial 2nd dimension of the array.

If you wish to "super-decay" a multi-dimensional array to a pointer to its first value, then simply do that yourself:

check = strip(&signalstnV[0][0][0]);

Upvotes: 5

Related Questions