I am trying to pass a two dimensional array to a function and modify it. I understand that two dimensional arrays are automatically pass-by-reference parameters so that solves half of the problem. However, when I try to compile the code:

#include <cstdlib>
#include <iostream>

using namespace std;

int x, y;

void changeArray(int array[][y]){
    array[1][1] = 5;
}

int main(int argc, char** argv) {
    x = 5, y = 4;
    int array[4][5];
    changeArray(array);
    return 0;
}

I get the error "array bound is not an integer constant". I have researched this problem online and only found solutions for when the array is declared with numbers as dimensions, not variables.

I am trying to pass a two dimensional array to a function and modify it. I understand that two dimensional arrays are automatically pass-by-reference parameters so that solves half of the problem. However, when I try to compile the code:

#include <cstdlib>
#include <iostream>

using namespace std;

int x, y;

void changeArray(int array[][y]){
    array[1][1] = 5;
}

int main(int argc, char** argv) {
    x = 5, y = 4;
    int array[4][5];
    changeArray(array);
    return 0;
}

I get the error "array bound is not an integer constant". I have researched this problem online and only found solutions for when the array is declared with numbers as dimensions, not variables.

Every dimension except the first must be a constant. A constant is handled at compile time. When you attempt to declare array like "int array[4][5]", those numbers are not dealt with until you run the program.

The problem is memory related. Internally, when you declare an 1d array such as "int array[4]" this is perfectly fine, since your computer knows how many bytes an integer takes up. It makes a table of sizes so it can iterate through these arrays when you compile it. So therefore it makes it possible to say "cout << array[3]" because your program knows "ok, we know from our table that this array contains elements that are exactly 1 integer long, so lets go 3 int-length memory spaces to the right and output the data".

But when you declare a 2d array such as "int array[4][5]", the "5" represents the number of ints in each of the [4] elements, or in other words, what the final size of each of the 4 elements will be. But the 5 is not known during compile, so it cannot build a table of how big it is, and therefore doesn't know how much memory to "skip" when you access an element not at the front, and also doesn't know how far to go before stopping after accessing an element.
-Greywolf

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.