【问题标题】:CS50 pset5 hashtable nodesCS50 pset5 哈希表节点
【发布时间】:2019-07-14 20:29:57
【问题描述】:

我正在开发 pset5 的哈希表版本。我无法将单词值分配给我创建的节点。在这个while循环之外我没有改变任何东西。我从以下行收到错误消息: node_ptr->word = word;它给出了一个错误“错误:数组类型'char [46]'不可分配。”为什么这条线不起作用?

// Buffer for a word
char word[LENGTH + 1];

// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
    //1) Create a node
    node *node_ptr = malloc(sizeof(node));

    //check memory != NULL
    if (!node_ptr)
    {
        return 1;
    }

    //assign values to node 
    node_ptr->word = word;
    node_ptr->next = NULL;

【问题讨论】:

  • 很难说没有看到node 是如何定义的。考虑使用minimal reproducible example。如果您尝试将数据从一个字符数组复制到另一个字符数组,请考虑strcpy
  • 一般EOF 不是fscanf 的唯一故障模式。在您的情况下,这将导致文件中最后一个单词之后出现垃圾字符串。检查匹配参数的数量 (!= 1)

标签: c hashtable cs50


【解决方案1】:

问题是节点结构内的数据成员word。我认为您的 node 定义为

struct node
{
     char word[46];
     struct node_ptr *next;
};

所以这种情况node_ptr->word 不是可修改的左值。因此,当您分配node_ptr->word = word 时,这意味着您违反了此规则。您正在尝试修改一个不可修改的左值(node_ptr->word 现在是左值)。您应该使用 strcpy 将字符串从 word 复制到 node_ptr->word 是一种更好的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 2015-12-10
    • 2016-01-06
    相关资源
    最近更新 更多