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

1
  • 1
    This is not possible in Standard C++. VLA is a C-only feature, or non-standard compiler extensions. Link to related question Commented Nov 3, 2014 at 21:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 the body of the function must be in a header file. You may have to #include <cstddef> to get size_t, or replace size_t with unsigned if arrays of size 2^32 are large enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.