简体   繁体   中英

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.

What I am trying to do?

I am trying to access the items variable as an array from an instance of the HashTable struct.

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:

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:

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

You are allocating an array of pointers to 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));

In the above line what you are trying to do is creating a size no of items. which is pointed by a pointer of type hashTable->items for which it need not be a double pointer if your traversing the struct.

change Item **items; to 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

hashTable->items = calloc (size, sizeof(Item *)); // create size no of pointers

and then create each of the Item struct in loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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