0

I once saw code (from a source apparently reliable enough to cause me to remember it) that seemed to convey the length of the array while passing them in a funtion (See example below):

void foo(int [m][n] array)
{
//m and n are the rows and columns of the array
//code
}

However, I'm unable to find that source and am beginning to wonder if I got it all wrong and maybe, even imagined it? Can someone care to comment?

hexcode
  • 393
  • 1
  • 4
  • 13

3 Answers3

6

You can use templates to deduce the static size from the argument if you accept the array by reference:

template<std::size_t X, std::size_t Y>
void print(int(&array)[X][Y])
{
    for(std::size_t x = 0; x < X; ++x)
    {
        for(std::size_t y = 0; y < Y; ++y)
            std::cout << ' ' << array[x][y];
        std::cout << '\n';
    }
}

int main()
{
    int array[][3] = {{1, 3, 5}, {2, 4, 6}};

    print(array);
}

Output:

 1 3 5
 2 4 6
Galik
  • 47,303
  • 4
  • 80
  • 117
  • 1
    @hexcode No, the size of dynamically created arrays is not deducable, you simply have to get it right manually. – Galik Oct 27 '16 at 23:06
1

In C++ you can do

void foo(int array[m][n])

as long as both m and n are integral constant expressions. m will be ignored, while n will affect the parameter type. The above is equivalent to

void foo(int array[][n])
void foo(int (*array)[n])

Whether this is similar to what you saw - only you can know.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

does the preceding line look something like the following?

template <size_t m, size_t n>

The compiler will create a uniquely named version of the function for each array size used.

Caleth
  • 52,200
  • 2
  • 44
  • 75