【发布时间】:2010-10-11 20:58:27
【问题描述】:
我正在尝试创建一个指针数组。这些指针将指向我创建的 Student 对象。我该怎么做? 我现在拥有的是:
Student * db = new Student[5];
但该数组中的每个元素都是学生对象,而不是指向学生对象的指针。 谢谢。
【问题讨论】:
我正在尝试创建一个指针数组。这些指针将指向我创建的 Student 对象。我该怎么做? 我现在拥有的是:
Student * db = new Student[5];
但该数组中的每个元素都是学生对象,而不是指向学生对象的指针。 谢谢。
【问题讨论】:
Student** db = new Student*[5];
// To allocate it statically:
Student* db[5];
【讨论】:
Student* db[5] 和Student** db = new Student*[5] 有什么相同之处?使用其中一个有什么好处?
#include <vector>
std::vector <Student *> db(5);
// in use
db[2] = & someStudent;
这样做的好处是您不必担心删除分配的存储空间 - 向量会为您完成。
【讨论】:
指针数组写成指针的指针:
Student **db = new Student*[5];
现在的问题是,您只为五个指针保留了内存。因此,您必须遍历它们以自己创建 Student 对象。
在 C++ 中,对于大多数用例来说,使用 std::vector 会更轻松。
std::vector<Student*> db;
现在您可以使用 push_back() 来添加指向它的新指针,并使用 [] 来索引它。使用起来比**的东西干净。
【讨论】:
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
}
【讨论】: