Tilted Forum Project - TFP - Sexuality, Philosophy and Political Discussion

Go Back   Tilted Forum Project - TFP - Sexuality, Philosophy and Political Discussion > Interests > Tilted Technology

Reply
 
LinkBack Thread Tools
Old 03-15-2005, 01:10 PM   #1 (permalink)
Beyond Belief
 
CSflim's Avatar
 
Join Date: Apr 2003
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 02:15 PM.
CSflim is offline   Reply With Quote
Old 03-16-2005, 09:24 PM   #2 (permalink)
It's Just A Game
 
n0nsensical's Avatar
 
Join Date: Sep 2003
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.
__________________
The spice must flow...

"My friends I will have an energy policy that we will be talking about, which will eliminate our dependence on oil from the Middle East that will – that will then prevent us – that will prevent us from having ever to send our young men and women into conflict again in the Middle East."
--John McCain May 2nd 2008
n0nsensical is offline   Reply With Quote
Old 03-17-2005, 11:26 AM   #3 (permalink)
Beyond Belief
 
CSflim's Avatar
 
Join Date: Apr 2003
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   Reply With Quote
Old 03-17-2005, 01:51 PM   #4 (permalink)
kel
WARNING: FLAMMABLE
 
Join Date: Apr 2003
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   Reply With Quote
Old 03-18-2005, 12:37 AM   #5 (permalink)
It's Just A Game
 
n0nsensical's Avatar
 
Join Date: Sep 2003
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.
__________________
The spice must flow...

"My friends I will have an energy policy that we will be talking about, which will eliminate our dependence on oil from the Middle East that will – that will then prevent us – that will prevent us from having ever to send our young men and women into conflict again in the Middle East."
--John McCain May 2nd 2008

Last edited by n0nsensical; 03-18-2005 at 12:41 AM.
n0nsensical is offline   Reply With Quote
Old 03-18-2005, 02:07 AM   #6 (permalink)
Insane
 
Join Date: May 2003
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   Reply With Quote
Old 03-18-2005, 07:46 AM   #7 (permalink)
Beyond Belief
 
CSflim's Avatar
 
Join Date: Apr 2003
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   Reply With Quote
Old 03-24-2005, 12:35 AM   #8 (permalink)
Crazy
 
Join Date: Apr 2004
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   Reply With Quote
Old 03-30-2005, 07:23 PM   #9 (permalink)
Rookie
 
Join Date: Jan 2005
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   Reply With Quote
Reply

Bookmarks

Tags
array, bounds

Thread Tools

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
Forum Jump


All times are GMT -7. The time now is 02:05 PM.


Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0
All text (c) 2002-2008 Tilted Forum Project
"Insignia" vBulletin 3.5 - b6gm6n - x7x7x7.com