First, note that variable length arrays (VLAs) are not standard C++. The fact that this line compiles is due to a GCC compiler extension:
bool myArray[size][size];
It simply isn't valid C++. The dimensions of your array need to be compile time constants, yet here you're using arguments passed to your function build
.
Anyway, to pass a VLA to a function, you have to continue using compiler extensions. However, as far as I've tested, these only work when compiling as C. The first option uses an extension that allows parameters to be used in other parameter declarations:
void modify(int mySize, bool array[][mySize]);
The second option, if you want mySize
to be the second argument, also uses a compiler extension allowing forward declarations of parameters:
void modify(int mySize; bool array[][mySize], int mySize);
Here int mySize;
is a parameter forward declaration.
Nonetheless, you really shouldn't be using variable length arrays. You can dynamically allocate arrays of variable length, like so:
void modify(bool** array, int mySize);
void build(int size) {
bool** myArray = new bool*[size];
for (int i = 0; i < size; i++) {
myArray[i] = new bool[size];
}
modify(myArray, size);
}
However, this is still not a recommended practice in C++. You should avoid dynamic allocation unless you really need it, and when you do need it you should manage it in some way. Here, you would need to remember to delete[]
each element of myArray
and myArray
itself.
What you should really be using is the standard containers. A std::vector<std::vector<bool>>
would suit you well here:
void modify(std::vector<std::vector<bool>>& array);
void build(int size) {
std::vector<std::vector<bool>> myArray(size, std::vector<bool>(size));
modify(myArray);
}
Now you don't even have to pass along the size.