By Saumya Sambit Acharya

2017-08-01 07:06:35 8 Comments

template <size_t size_x, size_t size_y>

int func(int(&grid)[size_x][size_y], int s_x, int x)
    if (s_x == x)
        return 0;
    else {
        cout << grid[s_x][0] << " " << x << endl;
        return func(grid, s_x, x);

int main()
    int T;
    cin >> T;
    while (T > 0) {
        int M, N, x, y, s_x = 0, s_y = 0;
        cin >> M >> N;
        int grid[M][N] = {};
        cin >> x >> y;
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                cin >> grid[i][j];
        int time_r = func(grid, s_x, x);
        cout << time << endl;
    return 0;

Errors I'm getting:

no matching function for call to ‘func(int [M][N], int&, int&)’ int time_r=func(grid,s_x,x);

note: candidate: template int func(int (&)[size_x][size_y], int, int) int func(int (&grid)[size_x][size_y],int s_x, int x)

note: template argument deduction/substitution failed:

note: variable-sized array type ‘long int’ is not a valid template argument int time_r=func(grid,s_x,x);

How to run it properly?


@cmaster 2017-08-01 08:29:30

The problem is, that M and N are runtime values, and C++ cannot handle array types with dynamic size correctly. You are allowed to create a stack-based array of dynamic size as you did, but that's about it. You cannot pass a pointer to your 2D array around, as C++ forbids you to use the type int (*)[N].

There are a few workarounds to this:

  • Do the indexing yourself, passing a flat 1D-array.

  • Use an array of pointers, so that all pointer arrays themselves are 1D arrays.

  • Use a vector of vectors.

  • Fall back to C, which can easily handle runtime array sizes since C99.

@MicroVirus 2017-08-01 08:24:53

This is an odd mix of C99 VLAs and C++ templates. The template expects an array with bounds known at compile time, whilst the VLA only knows its bounds at runtime, so this will not work.

You can either go the C way and use a normal (non-template) func that takes a pointer and two sizes, or you throw your entire code around and go the C++ way, preferably using vectors.

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] How do you set, clear, and toggle a single bit?

16 Answered Questions

[SOLVED] Can templates only be implemented in header files?

76 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2119444 View
  • 2852 Score
  • 76 Answer
  • Tags:   c++ string split

27 Answered Questions

[SOLVED] What is tail recursion?

1 Answered Questions

[SOLVED] C++: No matching function call when calling tuple_transpose function

2 Answered Questions

1 Answered Questions

1 Answered Questions

1 Answered Questions

[SOLVED] How to implement StringBuilder class which to be able to accept IO manipulators

  • 2015-01-16 15:47:42
  • bobeff
  • 521 View
  • 0 Score
  • 1 Answer
  • Tags:   c++ stl

3 Answered Questions

Sponsored Content