Search code examples
c++arraysvariable-length-array

C++ Passing Dynamic Array Determined by Parameter


This function has been asked a few times on here but I am interested in a particular case. Is it possible to have the size of the array passed defined by an additional argument?

As an example, let's say I want a function to print a 2D array. However, I the array may not have the same dimensions every time. It would be ideal if I could have additional arguments define the size of that array. I am aware that I could easily switch out the n for a number here as needed but if I have more complex functions with separate header files it seems silly to go and edit the header files every time a different size array comes along. The following results in error: use of parameter 'n' outside function body... which I understand but would like to find some workaround. I also tried with g++ -std=c++11 but still the same error.

#include <iostream>
using namespace std;

void printArray(int n, int A[][n], int m) {
    for(int i=0; i < m; i++){
        for(int j=0; j<n; j++) {
            cout << A[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {

    int A[][3] = {
        {1,2,3},
        {4,5,6},
        {7,8,9},
        {10,11,12}
    };

    printArray(3, A, 4);

    return 0;
}

Supposedly, this can be done with C99 and also mentioned in this question but I cannot figure out how with C++.


Solution

  • This works:

    template<size_t N, size_t M>
    void printArray( int(&arr)[M][N] ) {
      for(int i=0; i < M; i++){
        for(int j=0; j < N; j++) {
          std::cout << A[i][j] << " ";
        }
        std::cout << std::endl;
      }
    }
    

    if you are willing to put the code in a header file. As a bonus, it deduces N and M for you.