2013-03-30 36 views
-1

我有這樣的代碼:如何分配兩個指向Struct的指針?

struct human 
    { 
     string name; 
     string adress; 
     string com_name; 
     string com_adress; 
    }; 
    human **arr_human; 

我需要分配指針數組。 我試試這個:

arr_human = new human * [ 1000 ]; 

,但我不能使用這個結構(例如:

arr_human[0]->name = oName; 
arr_human[0]->adress = oAddr; 
arr_human[0]->com_name = cName; 
arr_human[0]->com_adress = cAddr; 

爲什麼

+0

你只分配了指針,而不是它們應該指向的對象。 'for(int i = 0; i <1000; ++ i)arr_human [i] = new human;' – jrok

+0

而且無論如何...'std :: vector vec; vec.resize(1000);' – 2013-03-30 22:44:17

回答

3

像羅說,你分配的指針,但是沒有對象?你可能想要做這樣的事情:

for (int i = 0; i < 1000; i++) 
    arr_human[i] = new human[numObjectsYouWant]; 

既然你使用的是C++,那麼你也可以使用載體雖然。消除使用原始指針時可能遇到的許多問題。

vector<human> arr_humans; 
相關問題