0

This code

int[][] settile(int[][] field, int x, int y, bool player);

in a header file gives the following errors:

expected an identifier

at the first [],

an array may not have elements of this type

at the second [] and

expected a ';'

at settile. Where are the errors and how can I fix this?

h h h
  • 15
  • 4

2 Answers2

0

In a short: you can't return and pass a 2D array in these ways. Use vectors (or array of vectors as @formerlyknownas_463035818 suggested in comments).

An array is a linear part of a memory. [] operator takes value in memory by some offset. So it's equals arr[i] == *(arr + i). For 2D arrays, the compiler needs to know all but one dimension so compile can use it like this: arr[i][j] == *(arr + i * N + j). When you pass array in function you must specify sizes of all but one (or all, you want) dimensions. I.e. void f(int a[][5]);

About returning 2D arrays. Array in C++ isn't a type, it's a special form of declaration. So returning int[][] just doesn't make sense. You have to use some kind of wrapper (such as std::array of std::vector), which will copy all the data.

P. Dmitry
  • 1,123
  • 8
  • 26
  • your suggestion to use vectors can be slightly misleading, because `std::array` can work as well – 463035818_is_not_an_ai Oct 07 '19 at 17:57
  • 1
    yes, but its not clear from the question if that is the case. Passing the 2d vector is also wrong in OPs code, because the first dimension has to be fixed (and no size is passed as parameter), so it could well be that the size is fixed. In any case dynamic or fixed size is orthogonal to the problem of returning a 2d array/vector in OPs code – 463035818_is_not_an_ai Oct 07 '19 at 18:00
0

You could be returning and passing as a parameter a dynamic array which is basically an array of pointers.

Syntax:

int** settile(int** field, int x, int y, bool player);

see more about 2D dynamic array here How do I declare a 2d array in C++ using new?

Josh W.
  • 102
  • 7