0

I'm working on some passing of arrays in C++. The following works, provided I define the array with numbers such as:

 gen0[6][7]. 

But, I cannot call the method where I send a variable as my size parameters. I realize that I probably need to something with passing them as pointers or by reference. I read elsewhere to use unsigned int, didn't work. I tried a few variations, but I'm struggling with the whole concept. Any tips/advice would be greatly appreciated!

//in main
 int col1, col2;
 col1 = rand() % 40 + 1;
 col2 = rand() %  50 +1;
 int gen0[col1][col2];
 print(gen0)

//not in main
 template<int R, int C>
 void print(int (&array)[R][C])
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Are you getting an error? What is the problem exactly? – David G Sep 26 '14 at 03:38
  • Look into how to allocate (and deallocate!) arrays of values on the heap with `new[]` and `delete[]` -- this will let you use a size determined at runtime instead of compile time. – Cameron Sep 26 '14 at 03:57
  • 1
    VLA (variable length arrays) you're defining isn't part of the C++ standard. Don't expect it to work like it is. They're provided as an implementation extension. Template provision is done at *compile-time*. your array dimensions are defined at *run-time*. My advise is to use a `std::vector>` and spin an iterator based solution for printing. – WhozCraig Sep 26 '14 at 04:00

1 Answers1

1

VLA (variable length arrays) is an extension of some compiler and it is done at runtime.

whereas:

template<int R, int C> void print(const int (&array)[R][C])

is the correct way to pass multi-dimensional array by reference, this is done at compile time and is incompatible with VLA.

A possible alternative would be to use std::vector:

std::vector<std::vector<int>> gen0(col1, std::vector<int>(col2));

And

void print(const std::vector<std::vector<int>>& array)
Jarod42
  • 203,559
  • 14
  • 181
  • 302