1

So I'm trying to create a function that takes a 2d array as input along with Rows and Cols variables and output the contents of the array in a table format. This is what I have so far

#include <iostream>
using namespace std;

void Tabulate(int *x[][], int xRows, int xCols) {
  for (int i = 0; i < xRows; i++) {
    for (int j = 0; j < xCols; j++) {
      cout << x[i][j] << "\t";
    }
    cout << endl;
  }
}

int main() {
  int rows = 2;
  int cols = 3;
  int x[rows][cols] = {{2,3,4}, {8,9,10}};
  Tabulate(x, rows, cols); 
}

and here are the errors it's returning

tabulate.cpp:4:20: error: declaration of ‘x’ as multidimensional array must have bounds for all dimensions except the first
    4 | void Tabulate(int *x[][], int xRows, int xCols) {
      |                    ^
tabulate.cpp:4:25: error: expected ‘)’ before ‘,’ token
    4 | void Tabulate(int *x[][], int xRows, int xCols) {
      |              ~          ^
      |                         )
tabulate.cpp:4:27: error: expected unqualified-id before ‘int’
    4 | void Tabulate(int *x[][], int xRows, int xCols) {
      |                           ^~~
make: *** [<builtin>: tabulate] Error 1

I KNOW it's having to do with the syntax of defining the second dimension of the array but I'm having trouble finding anything for my specific case. Sorry if it's something stupid that i'm missing but I'd appreciate the help :/.

Cisc0gif
  • 15
  • 5

1 Answers1

0

You are trying to pass a 2D array to a function. In that case either your array should be dynamic or one dimension constant.

Use this:

void Tabulate(int **x, int xRows, int xCols) //dynamic array

See more details/method here(there are some really great answers here): Passing a 2D array to a C++ function

avinal
  • 54
  • 2
  • 8
  • Thank you so much! It's so much easier using templates to define the data type of the array in the function arguments instead! – Cisc0gif Mar 09 '21 at 05:36
  • Yeah, that is true, I just answered your specific case. Please mark it as solved so that another developer can focus on a different question. – avinal Mar 09 '21 at 16:26