指向链接列表指针数组的指针

时间:2010-10-28 20:00:25

标签: c arrays pointers malloc

嘿伙计们 右,所以我一直在这个问题在过去的6小时,一直打到拼了命也没有用谷歌。 对,我需要一个指向数组的指针。此数组包含指向链接列表的指针。我将不得不对它进行malloc,因为直到运行时我才知道数组大小。

LList **array

这是我的第一个想法,但这只是给了我一个LList数组的指针。或者至少这是我的理解。 有人可以帮我一把吗? 亚历

编辑: 确定如何使用它的一些信息。 我实现了一个非常基本的哈希表。 有一个结构包含指向链表的指针数组的指针。 它需要是一个指向数组的指针,这样当我调整表的大小时,我只需将指针更改为指向较大的表。

5 个答案:

答案 0 :(得分:5)

听起来你走在正确的轨道上。

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

array现在是指向LList的指针数组,而array[3]等元素将成为指向LList的指针。

数组中的数组和指针非常相似(但不完全相同!),如经典示例所示:*(array + 2)大部分等同于array[2]

修改 当您需要调整表格大小时,您只需要realloc额外的空间:

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

new_arrayold_array可能是也可能不是同一个指针,但无论哪种方式new_array都保证是指向足够空间来保存新数组的指针(或{{ 1}}如果无法分配内存)

第二次编辑: 正如user411313所提到的,如果你想要指向数组的实际指针,你需要获取数组的地址:

NULL

答案 1 :(得分: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.

这完全取决于你如何使用它。

答案 2 :(得分: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;

答案 3 :(得分:0)

指向指针的指针也可以是指针数组。


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

会使array成为指向LList的指针数组。然后array[i]将为您提供指向数组中第i个链接列表的指针。

答案 4 :(得分: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);