-1

Sorry if this is really easy to fix or a stupid question but I've only recently started programming.

So basicly in void main() I've declared a 2D array like so:

void main()
{
  const int grid = 5;
  array[grid][grid];
{

However I would like to pass this into a function like this:

void drawGrid(int grid, bool array[][])
{

}

This creates an error as the second parameter needs to have a number. But that's a problem since in main I declared my array using a variable.

void drawGrid(int grid, bool array[grid][grid])
{

}

Putting variables in the parameters does not work.

How do I go about passing the array to this function whilst using the int variable grid inside the parameters.

I have searched a lot and looked at answers from people who had similar problems to me but I just could not seem to figure out what to do specifically. Could anyone please show me how to fix the problem, I'd be incredibly greatful as I've been trying to work this out for almost two hours now. Thanks.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Roixen
  • 1
  • 1
  • What's the error message? Anyway, I think this is just a simple scoping problem. Just put `grid` in global scope. – cadaniluk Dec 27 '15 at 20:36
  • @cad "an array may not have elements of this type" is what happens if you leave the parameters empty. If you put grid in there, it is most definitely a scoping problem. However I do not want to declare this variable globally (and we are not allowed to either on my course) so I have to do it some other way. – Roixen Dec 27 '15 at 20:44

1 Answers1

0

You can use a function template with the size as the template parameter.

template <size_t grid>
void drawGrid(bool array[][grid])
{    
}

and call it simply with:

drawGrid(array);

or

drawGrid<grid>(array);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thank you if this works correctly, however I'd just like to know how a function template differs from just an ordinary function? Is there no way or passing grid into a normal function? – Roixen Dec 27 '15 at 20:47
  • In a function template, the size must be known at compile time. Hence, `bool array[][grid]` is a valid declaration. In a regular function, the size is not known until run time. Hence, `bool array[][grid]` is not a valid declaration. – R Sahu Dec 27 '15 at 20:49
  • Ok, thank you very much, I understand it now! – Roixen Dec 27 '15 at 20:52
  • @Roixen Note that you can specify both dimensions. The example here will accept `bool[N][grid]` for all values of `N`. – juanchopanza Dec 27 '15 at 21:03