我想創建一個鏈接結構數組,但我不知道如何填充這樣的數組。這是我想要做的一個例子。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;
不知道你的目標是什麼,但'new_foo - > next = array + i'''next'指向你要分配的數組元素。最終的結果是,每個'foo'鏈接到它自己並且迭代是無限的。也像篩子一樣泄漏,因爲'foo'是動態分配的,沒有被刪除。思考[一本很好的入門書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)可能是最好的選擇 – user4581301
是的,混合堆棧和動態分配isn'我想是個好主意。會給它一個閱讀謝謝你。你讓我意識到最好使用一個指針數組。 – camtorr95