1

I am writing a Conway's Game of Life in C++. I get a compile time error having something to do with the way I am passing 2-d arrays to methods:

gameoflife.cpp:5:25: error: array has incomplete element type 'int []'
void print_game(int game[][], int SIZE);

gameoflife.cpp:6:23: error: array has incomplete element type 'int []'
void run_game(int game[][], int SIZE);

gameoflife.cpp:7:23: error: array has incomplete element type 'int []'
void set_cell(int game[][], int i, int j, int next[][], int SIZE);

etc.

The beginning of my code is:

void print_game(int game[][], int SIZE);
void run_game(int game[][], int SIZE);
void set_cell(int game[][], int i, int j, int next[][], int SIZE);

Evidently the problem begins here.

What is the issue with passing a 2-d array in a method? Should I use a ** instead?

user3624730
  • 87
  • 1
  • 3
  • 5

3 Answers3

5

What is the issue with passing a 2-d array in a method? Should I use a ** instead?

Not really - if possible, you should use std::vector of vectors, like this:

#include <vector>
...
void print_game(std::vector<std::vector<int> > game) {
    ... // No need to pass the size
}

Passing a built-in 2D array would require you either to specify one of the two dimensions as a constant, or allocate an array as an array of pointers, and then pass a pointer to pointer (i.e. int **). Neither of these choices is optimal: the first limits your array to a compile-time maximum, while the second requires you to do a decent amount of manual memory management.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You cannot pass an array of array's without specifying the size first, or passing them as a pointer. the best you could do would be

array[][5] //doesn't HAVE to be five, just example value

highly recommend taking @dasblinkenlight's route however, using two dimensional arrays should be avoided c++.

jrok
  • 54,456
  • 9
  • 109
  • 141
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
0

This

int game[][]

is a declaration of an array of incomplete type because size of element for example game[0] of the array is unknown. You have to specify sizes of all dimensions except the leftmost using constant expressions.

If for example SIZE is defined as a constant and the array has equal dimensions then you could write for example

void print_game(int game[][SIZE], int SIZE);

or

void run_game(int game[][SIZE], int SIZE);

and so on.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335