1

I know that there are multiple answers on this particular subject but I am yet to find something that works for my use case.

I have a 2D array (9x9) that I need to pass into a function by reference so that it can be stored in the main program after the function is done with it.

Here is the function declaration:

void ReadFile(ifstream& infile, string fileName, string filePath, int array[9][9]) // Opens, reads, outputs and closes the file

The file I am opening is a 9x9 grid of numbers, I need to store that grid into a local variable (9x9 array of integers) within main.

Anybody know how I can go about this?

James

James
  • 69
  • 1
  • 9
  • 4
    This is C++, use [`std::array`](http://en.cppreference.com/w/cpp/container/array) instead. – O'Neil Apr 01 '18 at 23:06
  • The answer is "Yes." – Jive Dadson Apr 01 '18 at 23:38
  • 1
    What keeps you from passing a reference? The function declaration would be `void ReadFile(ifstream& infile, string fileName, string filePath, int (&array)[9][9]);` (note the `&` before `array`; parentheses are necessary to avoid an -- impossible and unwanted -- array of references). – Peter - Reinstate Monica Apr 02 '18 at 00:41

1 Answers1

2

I would drop the C-style array in favor of the C++ std::array, if you have access to C++11 features:

#include <array>

using Array = std::array<std::array<int, 9> 9>;

void ReadFile(ifstream& infile, string fileName, string filePath, const Array& array);

Then in your function, you can copy this array like any other variable. You also get all sorts of goodies, like the size() method, and iterator access. From cppreference (see link above):

The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc.

BobMorane
  • 3,870
  • 3
  • 20
  • 42