2017-03-27 57 views
0

我想創建一個鏈接結構數組,但我不知道如何填充這樣的數組。這是我想要做的一個例子。C++中的鏈接結構數組

struct foo { 
    int data; 
    foo* next; 
}; 

我想數組聲明環

while(1) { 
    foo array[n]; 
    // init array, data to -1 and next to NULL; 

我喜歡把它裏面的東西里面,在某種程度上創造的foo新實例所有FOO在指數掛鉤我有一個共同的財產。

foo* new_foo = new foo; 
    new_foo -> data = x; 
    new_foo -> next = array + i; // index 
    array[i] = *new_foo; 

    //do things 
    iterate(array); 

    //delete[] array; maybe 
} // end loop, start again with a new array. 

迭代方法會是這樣的。

for(int i=0; i<n; ++i) { 
    foo* iter = array + i; 
    while(iter != NULL) { 
     //do things 
     iter = iter -> next; 
    } 
} 

它根本不起作用,迭代方法進行無限循環。錯誤可能在其他地方,但我仍然不知道這是否是正確的方式。我知道我也必須在某處使用刪除。我仍然是新來的C++,我很樂意提供任何建議。謝謝!

編輯:

這工作正常,如果有人想知道。

foo* array[n] = {NULL}; 

foo* new_foo = new foo; 
new_foo -> data = x; 
new_foo -> next = array[i]; 
array[i] = new_foo; 
+1

不知道你的目標是什麼,但'new_foo - > next = array + i'''next'指向你要分配的數組元素。最終的結果是,每個'foo'鏈接到它自己並且迭代是無限的。也像篩子一樣泄漏,因爲'foo'是動態分配的,沒有被刪除。思考[一本很好的入門書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)可能是最好的選擇 – user4581301

+0

是的,混合堆棧和動態分配isn'我想是個好主意。會給它一個閱讀謝謝你。你讓我意識到最好使用一個指針數組。 – camtorr95

回答

1

從我的理解通過您的問題,您需要一種方法來填充鏈接的結構,並遍歷它。糾正我,如果我錯了。

可以說,如果你想填充n個結構。

foo* new_foo = new foo; 
new_foo -> data = 1; 
foo* head = new_foo; // store a starting pointer to the linked list 
foo* prev = new_foo; 
i=2; 
while(i<=n) 
{ 
    foo* new_foo = new foo; 
    new_foo -> data = i++; 
    prev -> next = new_foo; 
    prev=new_foo; 
} 
prev->next=NULL; 

現在,如果你想迭代並對事件進行填充列表。現在

foo* iter =head; 
while(iter!=NULL) 
{ 
    //do things 
    iter=iter->next; 
} 

如u想這樣的鏈接結構的數組,可以存儲陣列中的所有鏈接結構的頭指針。

+0

考慮到問題的性質,很好的解決了答案。有用於鏈表的數組。哈希表是常見的表。 – user4581301

+0

是的,我同意,對此抱歉。修改了答案,謝謝。 – Chandini

+0

謝謝你們兩位!在堆棧中創建的只是改變引用的值,並且不會在鏈接鏈中被推回,從而引用自身並無限循環。所以像這樣存儲頭指針就像一個魅力。 – camtorr95