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

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

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.

回答1:

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

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



回答2:

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



回答3:

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

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 }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!