简体   繁体   English

无法从C中的结构以数组形式访问**变量

[英]Can't access ** variable as an array from a struct in C

First off this is a difficult question to articulate as I'm not greatly familiar with C and I have searched around but I'm also not familiar with the lingo for C. Also the code compiles fine without any warnings or errors. 首先,这是一个很难解决的问题,因为我对C不太熟悉,我已经四处搜寻,但是我对C的术语也不熟悉。代码也可以很好地编译,没有任何警告或错误。

What I am trying to do? 我要做什么?

I am trying to access the items variable as an array from an instance of the HashTable struct. 我试图从HashTable结构的实例作为数组访问项目变量。

These are the structs I'm using: 这些是我正在使用的结构:

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

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

My program breaks when I hit a piece of code that attempts to access the variables in the items array: 当我遇到一段尝试访问items数组中的变量的代码时,程序中断:

hashTable->items[index]->word

or 要么

hashTable->items[index]->count

This is the intializer: 这是初始化器:

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;
}

The last line before the return command should probably be: return命令之前的最后一行可能是:

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

You are allocating an array of pointers to Item . 您正在分配一个指向Item的指针数组。 So that would be the correct way of doing so. 因此,这将是正确的方法。 However, you still have to iterate the array somewhere and then initialize every item, before you can reference them. 但是,您仍然必须在某个地方迭代数组,然后初始化每个项目,然后才能引用它们。 Something as such: 这样的东西:

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

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

In the above line what you are trying to do is creating a size no of items. 在上面的行中,您要尝试创建的项目size为No。 which is pointed by a pointer of type hashTable->items for which it need not be a double pointer if your traversing the struct. hashTable->items类型的指针指向,如果您遍历该结构,则该指针不必是双指针。

change Item **items; 更改Item **items; to Item *items; Item *items;

If you want memory of each Item struct to stored and one more pointer pointing to the array of pointers.change the first line to 如果要存储每个Item结构的内存,并希望再有一个指针指向指针数组,请将第一行更改为

hashTable->items = calloc (size, sizeof(Item *)); hashTable-> items = calloc(size,sizeof(Item *)); // create size no of pointers //创建没有指针的大小

and then create each of the Item struct in loop. 然后在循环中创建每个Item结构。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM