views:

435

answers:

3

I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it? What I have now is:

Student * db = new Student[5];

But each element in that array is the student object, not a pointer to the student object. Thanks.

+13  A: 
Student** db = new Student*[5];
// To allocate it statically:
Student* db[5];
Mehrdad Afshari
I don't think the part to the right is correct in the second case. I think you mean `Student *db[5];`
FryGuy
@FryGuy: Thanks. corrected.
Mehrdad Afshari
+10  A: 
#include <vector>
std::vector <Student *> db(5);
// in use
db[2] = & someStudent;

The advantage of this is that you don't have to worry about deleting the allocated storage - the vector does it for you.

anon
While vector is the suggested way to have a list of stuff, strictly speaking, it's not an array.
Mehrdad Afshari
It can be used in every way that an array can be used. If it quacks like a duck, it's a duck.
anon
The vector will _not_ delete the allocated storage automatically, it will free the storage for the _pointers_ but not for the memory that the pointer points to. Use boost::ptr_vector for that.
Patrick Daryll Glandien
Did you read my example code? Should the storage pointed to by element [2] be deleted?
anon
+5  A: 

An array of pointers is written as a pointer of pointers:

Student **db = new Student*[5];

Now the problem is, that you only have reserved memory for the five pointers. So you have to iterate through them to create the Student objects themselves.

In C++, for most use cases life is easier with a std::vector.

std::vector<Student*> db;

Now you can use push_back() to add new pointers to it and [] to index it. It is cleaner to use than the ** thing.

ypnos