2010-02-15 63 views
5

我有下面的類如何在C++中動態分配指針數組?

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; 
} 

請告訴我如何我可以動態地在構造函數分配數組的指針 - 這個數組的大小將是最大範圍。

回答

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

但像往常一樣,你可能最好使用std ::指針向量。

2

這將是Nptr = new Node*[maxsize];另外,請記住在析構函數中使用delete[]

2

假設你要創建的3行4周的cols然後矩陣,

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 
}