03-15-2005, 12:10 PM | #1 (permalink) |
Sky Piercer
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.. |
03-16-2005, 08:24 PM | #2 (permalink) |
Junkie
Location: San Francisco
|
That is pretty much all you can do with C-style arrays. I highly recommend using STL vectors.
#include <vector> std::vector<int> v; // v is a vector of ints size 0 v.resize(5); // v is now a size 5 vector of ints v.size(); // returns the size of v (5 in this case) std::vector<float> u(10); // u is a size 10 vector of floats (you can leave out the std:: if you are doing either using namespace std; or using std::vector;) To pass a vector to a function, unless you want that function to have a copy of the original vector, pass a pointer to it or a reference (I recommend references unless you need the pointer functionality): void foo(std::vector<int> &v) { cout << v[0] << endl; } You can use a vector of vectors as a replacement for multidimensional arrays, but be careful because every vector has to be resized properly (which I guess you have to do for multidimensional arrays created with new anyway): std::vector<std::vector<int> > matrix; // you NEED the space between the two >s // if you want rows rows and cols columns: matrix.resize(rows); for (int r = 0; r < rows; ++r) matrix[r].resize(cols); Once you've done that you can just do matrix[0][1] etc. as usual to index it. Going back to C-style arrays, be careful with terminology. int** is a pointer to a pointer, not a reference to a reference (the syntax for pointers is from C while references are only in C++). In fact, it is impossible to have a reference to a reference. How to delete a int** depends entirely on how the memory was allocated. Basically, delete should be called on the same type as new returned, so if you have: int * x = new int; int ** px = &x; You would do delete *px; to free that memory or in this case: int * array = new int[6]; int ** parray = &array; delete [] *parray; or: int ** matrix = new int*[6]; for (int r = 0; r < 6; ++r) matrix[r] = new int[5]; yes, you would do like in your example to free it.
__________________
"Prohibition will work great injury to the cause of temperance. It is a species of intemperance within itself, for it goes beyond the bounds of reason in that it attempts to control a man's appetite by legislation, and makes a crime out of things that are not crimes. A Prohibition law strikes a blow at the very principles upon which our government was founded." --Abraham Lincoln |
03-17-2005, 12:51 PM | #4 (permalink) |
WARNING: FLAMMABLE
Location: Ask Acetylene
|
It depends on the situation, but you can have arrays of pointers to objects and leave the last position as null so it works like a c-string. You can also encapsulate the array in a struct with a size element. If the array points to structs your defining then you can work in some way to have one of those structs be an end marker of the array.
Generally you should just use a data structure that does this for you and not worry about how large or small it is.
__________________
"It better be funny" |
03-17-2005, 11:37 PM | #5 (permalink) |
Junkie
Location: San Francisco
|
Another nice thing about vectors is they do bounds checking for you, so you can avoid accidental overflows (and intentional overflows by people you don't want intentionally overflowing), also why it's good to use STL strings instead of char arrays.
__________________
"Prohibition will work great injury to the cause of temperance. It is a species of intemperance within itself, for it goes beyond the bounds of reason in that it attempts to control a man's appetite by legislation, and makes a crime out of things that are not crimes. A Prohibition law strikes a blow at the very principles upon which our government was founded." --Abraham Lincoln Last edited by n0nsensical; 03-17-2005 at 11:41 PM.. |
03-18-2005, 01:07 AM | #6 (permalink) |
Insane
Location: Austin, TX
|
kel's idea is pretty good if you're forced to use C-style arrays. Simply use something other than a for-loop to iterate over the array:
Code:
int x = 0; while(your_array[x] != NULL) { // do something with your_array[x] x++; } |
03-18-2005, 06:46 AM | #7 (permalink) | |
Sky Piercer
Location: Ireland
|
Quote:
That's another good idea. Thanks kel.
__________________
|
|
03-23-2005, 11:35 PM | #8 (permalink) | |
Crazy
Location: San Diego, CA
|
Quote:
Generally when working with arrays, you have to pass the size of the array. As for 2d arrays, to create one of dynamic size you have to do this: Code:
int ** my2darray = new (int*)[x_size]; for (int c = 0; c < y_size; c++) { my2darray[c] = new int[y_size]; } Code:
for (int c = 0; c < y_size; c++) { delete my2darray[c]; } delete my2darray; push_back() iterators Let's say T is a type and I have: vector<T> myVector; At the start, myVector.size() is 0 since it has no values. I can add values of type T to end of the vector with: myVector.push_back(value); Now let's say I want to loop through all the elements in the vector. The most efficient way is to use iterators: Code:
for (vector<T>::iterator i = myVector.begin(); i != myVector.end(); i++) { // (*i) contains the current value. You can basically treat i as a pointer } Code:
for (vector<T>::reverse_iterator i = myVector.rbegin(); i != myVector.rend(); i++) { // This loops through the vector backwards }
__________________
"Don't believe everything you read on the internet. Except this. Well, including this, I suppose." -- Douglas Adams |
|
03-30-2005, 06:23 PM | #9 (permalink) |
Upright
|
do not confuse references
void foo (int &name); with pointers void foo (int *name); Aside from that, you pretty much went over all you can do with C++ in the matter (save for using containers such as vectors, etc). references are marginally better (check Stroustrup for details), but that's what you have to play with. |
Tags |
array, bounds |
|
|