无法从C中的结构中访问**变量作为数组

时间:2014-04-04 04:05:03

标签: c pointers struct

首先,这是一个难以表达的问题,因为我不太熟悉C而且我已经搜索过但我也不熟悉C的术语。此外,代码编译良好,没有任何警告或错误。

我想做什么?

我试图从HashTable结构的实例访问items变量作为数组。

这些是我正在使用的结构:

typedef struct
{
    char *word;
    int count;
} Item;

typedef struct
{
    size_t size;
    size_t uniques;
    Item **items;
} HashTable;

当我点击一段试图访问items数组中的变量的代码时,我的程序中断了:

hashTable->items[index]->word

hashTable->items[index]->count

这是初学者:

HashTable *hashTable_new (int size)
{
    HashTable *hashTable = calloc (1, sizeof (HashTable));
    hashTable->size = size;
    hashTable->uniques = 0;
    hashTable->items = calloc (size, sizeof (Item));

    return hashTable;
}

2 个答案:

答案 0 :(得分:2)

return命令之前的最后一行应该是:

hashTable->items = calloc (size, sizeof(Item *));

您正在分配一个指向 Item 的指针数组。这样做是正确的方法。 但是,您仍然需要在某处迭代数组,然后初始化每个项目,然后才能引用它们。这样的东西:

for (size_t i = 0; i < hashTable->size; ++i)
{
    hashTable->items[i] = malloc(sizeof(Item));
}

答案 1 :(得分:1)

  

hashTable-&gt; items = calloc(size,sizeof(Item));

在上面一行中,您要做的是创建size个项目。它是由hashTable->items类型的指针指向的,如果遍历结构,它不需要是双指针。

Item **items;更改为Item *items;

如果你想要存储每个Item结构的内存,还有一个指针指向指针数组。将第一行改为

hashTable-&gt; items = calloc(size,sizeof(Item *)); //创建指针大小

然后在循环中创建每个Item结构。

 for (size_t i = 0; i < hashTable->size; ++i)
 {
      hashTable->items[i] = calloc(1,sizeof(Item));
 }