2010-10-28 149 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);