Tilted Forum Project Discussion Community  

Go Back   Tilted Forum Project Discussion Community > Interests > Tilted Technology


 
 
LinkBack Thread Tools
Old 03-15-2005, 12:10 PM   #1 (permalink)
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  
Old 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
n0nsensical is offline  
Old 03-17-2005, 10:26 AM   #3 (permalink)
Sky Piercer
 
CSflim's Avatar
 
Location: Ireland
Thanks for your help.
I've used vectors before and found them very useful. I never thought of using vectors of vectors!
__________________
CSflim is offline  
Old 03-17-2005, 12:51 PM   #4 (permalink)
kel
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"
kel is offline  
Old 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..
n0nsensical is offline  
Old 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++;
}
Of course this requires that you be unusually vigilant about ensuring that the NULL is always present at the end of the array. If you accidentally write a value to the last value of the array, the code will work fine until it hits one of these while loops, at which point you'll exit the bounds of the array (and probably segfault).
skaven is offline  
Old 03-18-2005, 06:46 AM   #7 (permalink)
Sky Piercer
 
CSflim's Avatar
 
Location: Ireland
Quote:
Originally Posted by kel
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.

That's another good idea. Thanks kel.
__________________
CSflim is offline  
Old 03-23-2005, 11:35 PM   #8 (permalink)
Crazy
 
Location: San Diego, CA
Quote:
Originally Posted by skaven
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++;
}
Of course this requires that you be unusually vigilant about ensuring that the NULL is always present at the end of the array. If you accidentally write a value to the last value of the array, the code will work fine until it hits one of these while loops, at which point you'll exit the bounds of the array (and probably segfault).
This doesn't work if 0 is an allowed value in the array. It's really only valid for strings.

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];
}
And so to delete it:
Code:
for (int c = 0; c < y_size; c++)
{
  delete my2darray[c];
}
delete my2darray;
As for vectors, I highly recommend looking a few things:
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
}
You can also make a reverse_iterator:
Code:
for (vector<T>::reverse_iterator i = myVector.rbegin(); i != myVector.rend(); i++)
{
  // This loops through the vector backwards
}
Have fun
__________________
"Don't believe everything you read on the internet. Except this. Well, including this, I suppose." -- Douglas Adams
Rangsk is offline  
Old 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.
Alita is offline  
 

Tags
array, bounds


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -8. The time now is 11:54 PM.

Tilted Forum Project

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project

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