【问题标题】:C - Errors when trying to make a hashtableC - 尝试制作哈希表时出错
【发布时间】:2016-02-12 03:05:24
【问题描述】:

我正在研究一个将字符串存储在链表中的哈希表,这样我就可以避免冲突。但是,我遇到了两个不知道如何解决的错误。我得到的第一个错误是在NewT->Table[i] == NULL; 的行中。上面写着warning: statement with no effects [-Wunused-value]

我得到的第二个错误是在同一个函数中。错误在return NewT 行中,错误为warning: return from incompatible pointer type[enabled by default]。我已经盯着这个看了一段时间,我看不出哪里有未使用的值,即使经过一些研究,我也不知道返回错误意味着什么。有人可以向我解释这些并帮助我解决它们吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define HASH_MULTIPLIER 65599

/*Structures*/
typedef struct List_T 
{
    char *str;
    int count;
    struct List_T *next;
} ListT;

typedef struct Hash_T
{
    int htsize;
    ListT **Table;
} HashT;

/*Prototypes*/
unsigned int hash(const char *str);
HashT **ht_create(void);

int htsize;

int main(int argc, char *argv[])
{
    if (argc <= 1)
    {
        printf("Please declare a table size");
        return 1;
    }
    htsize = atoi(argv[1]);
    return 0;
}
unsigned int hash(const char *str)
{
    int i;
    unsigned int h = 0U;

    for (i = 0; str[i] != '\0'; i++)
        h = h * HASH_MULTIPLIER + (unsigned char) str[i];

    return h % htsize;
}

HashT **ht_create(void)
{
    HashT *NewT;
    int i;

    if (htsize < 1) //invalid size for
    {
        fprintf(stderr,"Invalid Size for table");
        exit(0);
    }

    if ((NewT = malloc(sizeof(HashT))) == NULL)
    {
        fprintf(stderr,"Invalid size for table");
        exit(0);
    }

    if ((NewT->Table = malloc(sizeof(ListT *) * htsize)) == NULL)
    {
        fprintf(stderr,"Invalid size for table");
        exit(0);
    }

    for (i = 0; i<htsize; i++)
    {
        NewT->Table[i] == NULL;
    }

    NewT->htsize = htsize;

    return NewT;
}

【问题讨论】:

  • 在作业中删除一个 =。您正在返回 NewT,但是函数定义中的返回表明它应该是指向指针的指针,我的 c 有点生锈,但我认为它应该返回 &NewT 或更改签名以仅使用单个 *。
  • @aggaton:你是对的,虽然你可以给我你的投票——确实是无耻的广告:D
  • 很抱歉,当我从列表中找出问题时,我以为只有我一个人回答 :)

标签: c linked-list hashmap hashtable


【解决方案1】:

我遇到的第一个错误出现在NewT->Table[i] == NULL; 的行中。上面写着warning: statement with no effects [-Wunused-value]

显示此错误是因为代码进行的是比较,而不是赋值。比较返回的值(是Table[i]null?)本身没有分配给其他任何东西,这意味着它没有被使用。

保留一个 = 运算符而不是双倍的 ==,以确保您实际上是在分配而不是比较。

我得到的第二个错误是在同一个函数中。错误在 该行返回 NewT 并且错误是警告:return from 不兼容的指针类型[默认启用]。

您的函数声称要返回指向HashTHashT ** 的指针,但您最终返回的是指向HashTHashT * 的指针,而这正是@987654330 的类型@变量。

您的函数签名应该使用一个 * 而不是两个。

【讨论】:

  • 当我将函数签名更改为单个 * 时,我收到一条错误消息 error: conflicting types for 'ht_create'。还有其他提示吗?我通过返回语句return &amp;NewT; 尝试了其他用户的建议,但也出现了错误。还有其他建议吗?
  • @donutjuice:那你好像还有其他问题。我只是通过从前向声明 函数定义中删除单个 * 来尝试进行更改,并且它对我来说构建时没有错误。 (我之前只看过代码,没试过。)
猜你喜欢
  • 2023-03-15
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 2014-11-10
  • 2015-12-15
  • 1970-01-01
  • 2013-01-10
相关资源
最近更新 更多