2014-06-18 54 views
-6

我有這樣的結構:轉換malloc的新的C++結構

struct problem 
{ 
int length; 
struct node **x; 
};  

,我創造了這個結構的這樣一個結構:

struct problem prob; 

我可以在C這樣做:

prob.x = Malloc(struct node *,prob.length); 

但我怎麼能用c + +風格與new?爲什麼?

+0

向我們展示失敗的代碼。 – Erbureth

+0

是'Malloc'你自己的功能嗎? 'malloc'只能用於一個參數 – mch

+0

'prob.x = new node * [prob.length]'? – 101010

回答

0

好吧,這段代碼可能會奏效,請注意您不再持有指針的指針,但一個簡單的陣列 - 這可能會或可能不適合你正在嘗試做的工作:

typedef struct tagnode 
{ 
    ... 
} node; 

typedef struct tagproblem 
{ 
int length; 
node *x; 

tagproblem(int len) : length(len) 
{ 
    x = new node[length]; 
} 
~tagproblem() 
{ 
    delete [] x; 
} 
} problem; 

//Now create... 
problem = new problem(2); 
2

在C++中,可以通過這個來實現。

std::vector<node *> problem(length); 

告訴你的代碼是有效模擬的vector功能的一小部分。即,知道其大小的數組式容器。