2010-10-28 110 views
5

嘿傢伙 對,因此我一直在這個問題上過去6個小時,並一直打到谷歌像瘋了無濟於事。 正確的我需要一個指向數組的指針。該數組包含指向鏈接列表的指針。我將不得不malloc它,因爲我不知道數組大小,直到運行時。指向鏈接列表指針數組的指針

LList **array 

這是我的第一個想法,但這只是給了我一個指向一個數組的指針。或者至少這是我的理解。 有人能幫我一下嗎? 亞歷克斯

編輯: 確定一些信息將如何使用。 Im實現了一個非常基本的哈希表。 有一個結構包含一個指向鏈表的指針數組的指針。 它需要是一個指向數組的指針,這樣當我調整表格大小時,我可以將指針改爲指向較大的表格。

+0

本來在頂部,你說「的指針數組... [即]包含指向鏈表」但你的新的編輯現在說「一個指針鏈表的數組」。哪一個? – user470379 2010-10-28 20:18:26

+0

很好。重新編輯。指向指向鏈表的指針數組就是我要做的。 – Alex 2010-10-28 20:21:13

+0

我在下面編輯了我的回覆,以顯示如何調整它的大小。這是您新編輯背後的主要關注點,還是您想知道的其他內容? – user470379 2010-10-28 20:29:08

回答

5

這聽起來像你在正確的軌道上。

LList **array; 
array = malloc(num_ptrs * sizeof(LList*)); 

array現在是一個指針數組,以LList,和元素例如array[3]將是一個指向LList

數組和指針在C中非常相似(但不完全相同!),如經典示例所示:*(array + 2)大部分等價於array[2]

編輯: 當您需要調整表,你只需要realloc額外的空間:

LList **new_array; 
new_array = realloc(old_array, new_size * sizeof(LList*)); 

new_arrayold_array可能會或可能不會是相同的指針後,但無論哪種方式new_array保證是指向足夠空間來保存新陣列(或NULL,如果內存不能分配)

第2編輯: 作爲user411313提到,如果你想實際指向數組的指針,你需要採取數組的地址:

LList ***p_array; 
p_array = &array; 
+0

錯誤。問題是一個指向指向數組指針的指針。你的解決方案只是一個指向數組的指針。 – user411313 2010-10-28 20:33:38

+0

固定.......... – user470379 2010-10-28 20:36:41

0

指向對象的指針基本上與指向數組的指針相同。

int * blah; // an int pointer. It could point to an array of ints, or a single int. 
int ** blah; // a pointer to an int pointer. It could point to something that points to an int, or it could be pointing to an array of pointers to single ints, or it could be a pointer that points to an array of ints. 

這一切都取決於你如何使用它。

0

,如果你有寫自己的鏈表,你可以做到這一點。

typedef struct LLNode { 
    LLNode* next; 
    int  data; 
} LLNode; 

LLNode* linkedList = null; // a linked list 

LLNode** linkedListArray = (LLNode**) malloc(arraySize* sizeof(LLNode*)); 

LLNode*** pointerToLListArray = &linkedListArray; 

用鏈表庫:

LList* linkedListArray = (LList*) malloc(arraySize* sizeof(LList)); 

LList** pointerToLListArray = &linkedListArray; 
0

甲指針的指針也可以是一個指針數組。


int nLists; /* number of lists*/ 
LList **array; 
array = (LList **)malloc(nLists * sizeof(LList *)); 

將使array是一個指針數組,以LList。然後array[i]會給你指向數組中第i個鏈表的指針。

0
typedef struct LList LList; 
struct LList { 
int value; 
LList *next; }; 

LList *(*p)[3]; /* pointer to an array of 3 pointers to LList */ 
LList ll1 = {11}; 
LList ll2 = {22}; 
LList ll3 = {33}; 
size_t sizeofarray = sizeof*p/sizeof**p; /* calc arraysize at runtime here */ 
p = malloc(sizeofarray * sizeof**p); /* allocate space for each LList-pointer in array */ 
(*p)[0] = &ll1; 
(*p)[1] = &ll2; 
(*p)[2] = &ll3; 
/* test output here: */ 
printf("\n%d\n%d\n%d", ((*p)[0])->value,((*p)[1])->value,((*p)[2])->value); 
free(p);