View Single Post
Old 03-16-2005, 08:24 PM   #2 (permalink)
n0nsensical
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  
 

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