View Single Post
Old 03-15-2005, 12:10 PM   #1 (permalink)
CSflim
Sky Piercer
 
CSflim's Avatar
 
Location: Ireland
[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..
CSflim is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76