如何在 C++ 中动态分配指针数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2265664/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:46:44  来源:igfitidea点击:

How to dynamically allocate an array of pointers in C++?

c++

提问by Zia ur Rahman

I have the following class

我有以下课程

class Node
{
    int key;
    Node**Nptr;
public:
    Node(int maxsize,int k);
};
Node::Node(int maxsize,int k)
{
   //here i want to dynamically allocate the array of pointers of maxsize
   key=k;
}

Please tell me how I can dynamically allocate an array of pointers in the constructor -- the size of this array would be maxsize.

请告诉我如何在构造函数中动态分配指针数组——该数组的大小为 maxsize。

回答by

Node::Node(int maxsize,int k)
{
   NPtr = new Node*[maxsize];
}

But as usual, you are probably better off using a std::vector of pointers.

但像往常一样,您最好使用 std::vector 指针。

回答by Ashish

Suppose you want to create matrix of 3 rows and 4 cols then,

假设您要创建 3 行 4 列的矩阵,然后,

int **arr = new int * [3];  //first allocate array of row pointers

for(int i=0 ; i<rows ; ++i)
{
   arr[i] = new int[4]; // allocate memory for columns in each row
}

回答by Naveen

That will be Nptr = new Node*[maxsize];Also, remember to use delete[]in destructor.

那将Nptr = new Node*[maxsize];也是,记得delete[]在析构函数中使用。