C++ 如何创建指针数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/620843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create an array of pointers?
提问by chustar
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 对象。我该怎么做?我现在拥有的是:
Student * db = new Student[5];
But each element in that array is the student object, not a pointer to the student object. Thanks.
但是该数组中的每个元素都是学生对象,而不是指向学生对象的指针。谢谢。
回答by Mehrdad Afshari
Student** db = new Student*[5];
// To allocate it statically:
Student* db[5];
回答by chustar
#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.
这样做的好处是您不必担心删除分配的存储空间 - 向量会为您完成。
回答by ypnos
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.
现在的问题是,您只为五个指针保留了内存。因此,您必须遍历它们以自己创建 Student 对象。
In C++, for most use cases life is easier with a std::vector.
在 C++ 中,对于大多数用例,使用 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.
现在您可以使用 push_back() 向其添加新指针并使用 [] 对其进行索引。使用起来比**的东西更干净。
回答by user9546648
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
}