The simple answer is to use vector
s instead of arrays. C++'s rules for passing arrays as function parameters are esoteric and derived from C. Here are some of the issues:
- You can't use arrays for long without understanding and using pointers
Array subscripting is pointer subscripting. Arrays are accessed using pointer arithmetic. Arrays as function parameters are actually pointers in disguise.
- Functions don't get information about array size when taking an array argument
Consider the declaration:
void inc_all(int myarray[]); /* increments each member of the array */
Unfortunately, that array parameter is not an array parameter! It's actually a pointer parameter:
void inc_all(int *myarray); /* Exactly the same thing! */
And a pointer doesn't know how many items are in the sequence it points at. As a result this function cannot have the information necessary to know when the array stops. You either need to pass the length:
void inc_all(int *myarray, size_t len); /* size_t rather than int */
or you need to use a sentinel value to mark the end of the array. Either way, an array is not a self-contained encapsulated datatype like a vector
is.
- You can't pass an arbitrarily-sized two-dimensional array to a function
If you try to create a function which takes a two-dimensional array:
void inc_all(int myarray[][]); /* XXX won't compile! */
it won't compile. The problem is you have an indeterminate length array of indeterminate length arrays of int
s. The outer array doesn't know how large its members (the inner arrays) are and therefore doesn't know how to step through them in memory. You need to specify the size of the inner arrays:
void inc_all(int myarray[][10]);
at which point your code is probably not as general as you were hoping it was going to be.
If you use vector
s and vector
s of vectors
s, these problems don't arise because the vector
s themselves know how many members they have and carry that information with them.
If you still want to learn more about arrays and pointers I recommend section 6 of the comp.lang.c FAQ.