How do I create an array of pointers?

C++ArraysPointers

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

Student** db = new Student*[5];
// To allocate it statically:
Student* db[5];

Solution 2 - C++

#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.

Solution 3 - C++

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.

Solution 4 - C++

    void main()
    {
    int *arr;
    int size;
    cout<<"Enter the size of the integer array:";
    cin>>size;
    cout<<"Creating an array of size<<size<<"\n";
        arr=new int[size];
    cout<<"Dynamic allocation of memory for memory for array arr is successful";
    delete arr;
    getch();enter code here
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchustarView Question on Stackoverflow
Solution 1 - C++mmxView Answer on Stackoverflow
Solution 2 - C++anonView Answer on Stackoverflow
Solution 3 - C++ypnosView Answer on Stackoverflow
Solution 4 - C++user9546648View Answer on Stackoverflow