To add onto that article....
A 2D array is really an array of arrays.
It's easier to wrap your head around if you use typedefs for the arrays. But first... here's a 1D array example as an introduction to the problem:
1 2 3 4 5 6 7
|
void func(int[] ar); // pass an array of ints
int main()
{
short foo[10]; // have an array of shorts
func(foo); // ERROR, an array of shorts is not an array of ints. ILLEGAL
}
|
The error here is obvious. We have an array of shorts and we are trying to pass it as if it were an array of ints (which it's not). So there's a type mismatch... so it's an error.
With that in mind... let's use typedefs to turn arrays into a recognizable type:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
typedef int int4[4];
typedef int int5[5];
// now... int4 and int5 are type names which create arrays:
int4 arrayFour; // same as saying: int arrayFour[4];
int5 arrayFive; // same as saying: int arrayFive[5];
/////////////////////////
// now let's say we have a function which takes an array of int4s:
void func(int4[] array);
// and let's try to call it with some arrays:
int main()
{
int4 foo[3]; // an array of 3 int4s
func( foo ); // OK
int5 bar[3]; // an array of 3 int5s
func( bar ); // ERROR... int5 is not an int4. Type mismatch.
}
|
Just like the short/int example... int4 and int5 are two completely different types. So it's a type error, and the code will not compile.
The
exact same code without the typedefs is the problem you are seeing:
1 2 3 4 5 6 7 8 9 10
|
void func(int[][4] array); // func takes an array of int4s
int main()
{
int foo[3][4]; // an array of 3 int4s
func( foo ); // OK
int bar[3][5]; // an array of 3 int5s
func( bar ); // ERROR... int5 is not an int4. Type mismatch.
}
|
Herein lies the problem.
So this cannot be done without templates because the type is inconsistent. Different size arrays are different types.
However, it
can be done with templates because you can make the size of the array a template parameter. However this is a bad, bloated approach to the problem. A better approach would be to not use MD arrays (or objectify them in a class somehow).