0
int f(char* x)
{
    //something
}
int main(int argc,char** argv)
{
    char arr[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
    f(arr);
    return 0;
}

I can't expect how many dimensions of an array a programmer is going to pass. So I want to let this function get a multiple dimension array as a single parameter. Is it possible?

  • 2
    You'll need some information about the dimensions. You can pass it, but it won't be useful unless you know what is there. Maybe you should consider making a class that wraps your data and includes meta information that the programmers must provide. – matt May 12 '17 at 14:19

2 Answers2

0

You can achieve this by using templates to deduce the size of the array:

template<const std::size_t rows, const std::size_t cols>
int f(char (&arr)[rows][cols])

Your full code would look like this:

#include <cstdio>
template<const std::size_t rows, const std::size_t cols>
int f(char (&arr)[rows][cols])
{
    //something
}
int main(int argc,char** argv)
{
    char arr[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
    f(arr);
    return 0;
}

This might also be helpful: Passing a 2D array to a C++ function

Community
  • 1
  • 1
Gambit
  • 748
  • 8
  • 14
0

If you don't know the number of dimensions of the array, you'll have to get creative:

template <class T, std::enable_if_t<std::is_array<T>::value, int> = 0>
void f(T &arr) {
    constexpr auto dimensions = std::rank<T>::value;

    std::cout << "Received array with " << dimensions << " dimensions!";
}

You can use std::rank and std::extent to retrieve information about the array's geometry.

See it live on Coliru!

Quentin
  • 58,778
  • 7
  • 120
  • 175
  • Thank you. I'm really glad to know that there's what outputs the number of dimensions of an array. –  May 28 '17 at 01:54