0

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++.

Community
  • 1
  • 1
cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • 1
    This is not possible in Standard C++. VLA is a C-only feature, or non-standard compiler extensions. [Link to related question](http://stackoverflow.com/questions/22013444/are-variable-length-arrays-there-in-c) – M.M Nov 03 '14 at 21:51

1 Answers1

3

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • This works wonderful when in the main file, but I am having troubles when I put it in a header. Where it is complaining about 'M' and 'N' not being declared. Am I missing something? – cdeterman Nov 03 '14 at 21:37
  • @cdeterman the body of the function must be in a header file. You may have to `#include ` to get `size_t`, or replace `size_t` with `unsigned` if arrays of size `2^32` are large enough. – Yakk - Adam Nevraumont Nov 03 '14 at 21:38