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

后端 未结 3 1926
臣服心动
臣服心动 2020-12-10 15:35

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 wan         


        
相关标签:
3条回答
  • 2020-12-10 15:41

    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
    }
    
    0 讨论(0)
  • 2020-12-10 15:47
    Node::Node(int maxsize,int k)
    {
       NPtr = new Node*[maxsize];
    }
    

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

    0 讨论(0)
  • 2020-12-10 15:57

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

    0 讨论(0)
提交回复
热议问题