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
|