[c++] Array bounds.
I am coming to C++ from java.
What is the best way to pass arrays to functions when the size of the array is not known at compile time?
What about multidimensional arrays?
In java I can write a function for a class like so
public void foo(int[] myarray)
and in that function I can use:
myarray.length
to determine the bounds of the array, so it could be indexed with, say, a for loop:
for(int i=0; i<myarray.length; i++)
in c++ if the size of the array is not known at compile time, I have to use:
void myclass::foo(int *myarray)
if I don't know the size of the array I would have to include it
void myclass::foo(int *myarray, int size)
if I want to pass a two dimensional array:
void myclass::foo(int **my2Darray, int i, int j)
is there a better way to do this?
there is a potential danger in writing to my2Darray[x][y] as the user of the class may have provided incorrect values for i and j. What is the general convention in this regards? Should the writer of the function assume that the supplied values are valid?
I don't have a specific problem as such. I'm just wondering what is the best way to do things and what the accepted conventions are.
EDIT:
also, if I am using an int**, when I am finished with it, how do I delete it?
do I have to do:
for(int i=0; i<n; i++){
delete[] my2Darray[i];
}
delete[] my2Darray;
Using references to references (int**) seems quite a messy way to handle two dimensional arrays, especially compared with int[][].
Is there a better way to implement arrays when you don't know the size at compile time? Any general hints/tips on managing these?
__________________
Last edited by CSflim; 03-15-2005 at 01:15 PM..
|