我正在尝试创建一个指针数组。这些指针将指向我创建的Student对象。我该怎么做? 我现在拥有的是:
Student * db = new Student[5];
但该数组中的每个元素都是学生对象,而不是指向学生对象的指针。 感谢。
答案 0 :(得分:78)
Student** db = new Student*[5];
// To allocate it statically:
Student* db[5];
答案 1 :(得分:17)
#include <vector>
std::vector <Student *> db(5);
// in use
db[2] = & someStudent;
这样做的好处是您不必担心删除已分配的存储 - 向量会为您执行此操作。
答案 2 :(得分:11)
指针数组被写为指针指针:
Student **db = new Student*[5];
现在的问题是,你只为五个指针保留了内存。因此,您必须遍历它们以自己创建Student对象。
在C ++中,对于大多数用例,使用std :: vector生活会更容易。
std::vector<Student*> db;
现在你可以使用push_back()为它添加新指针,并使用[]来索引它。使用起来比使用起来更清洁。
答案 3 :(得分:0)
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
}