【问题标题】:Using the hash function使用哈希函数
【发布时间】:2012-05-09 09:23:11
【问题描述】:

我正在使用LINUX 做作业,我对哈希函数有一些疑问。 当我将*mnemonic_name 输入到'ADD' 之类的字符串中时,每次编译时find_index 都是随机的。你能解释一下这个问题并为我解决吗?

这是我的代码:

251  int symtab_finder(char *mnemonic_name)
252  {
253      node *temp;
254 
255      int find_index  =   op_find(mnemonic_name);
256      int find_flag   =   0;
257 
258      temp    =   optabl[find_index].head;
259 
260      while(temp)
261      {
262          if((strcmp(temp->mnemonic_name,mnemonic_name)==0))
263          {
264              find_flag   =   1;
265          }
266          temp    =   temp->next;
267 
268      }
269      if(find_flag == 0)
270      {
271 
272      }
273      printf("name %s, flag %d, find index %d\n",mnemonic_name,find_flag, find_index);
274      return find_flag;
275  }

当我将“ADD”之类的字符串放入“*mnemonic_name”变量时,输出“find_index”是随机的!我不知道为什么会这样。

下面是我的 op_find 代码。

 44  int op_find(char *mnemonic_name)
 45  {
 46      int op_index;
 47      int i;
 48      for(i=0; i< strlen(mnemonic_name); i++)
 49      {
 50          op_index += mnemonic_name[i];
 51      }
 52 
 53  //  printf("op_index is %d\n",op_index % 20);
 54      return op_index = op_index % 20;
 55  }
 56 
 57  int mn_find(char *opcode_number)
 58  {
 59      int opcode_value;
 60      opcode_value = hex_to_dec(opcode_number);
 61  //  printf("mne value is %d\n",((opcode_value/4)%20));
 62      return ((opcode_value/4)%20);
 63  }

【问题讨论】:

  • 你应该初始化你的变量。由于 op_index 没有初始化,它可能会得到一个随机值。
  • 哇!!弗朗西斯!谢谢!!这真的很难找到这个胆小的问题..再次感谢!
  • 只有大约每个编译器都会警告这种情况,所以总是使用-Wall
  • 你好 hroptayr!谢谢你的评论!但即使我在“makefile”中使用“-Wall”操作,我的 LINUX 机器也无法向我发出警告。无论如何,感谢您的好意,祝您有美好的一天!
  • 那么你在某处有问题(也许在你的makefile)。你真的应该总是使用-Wall,并且你应该避免大多数警告(极少数你不能避免的警告应该在代码中包含大的cmets以进行解释。 ...)

标签: c linux hash hashtable


【解决方案1】:

好的。因此,为了将其从“未回答”部分中删除,我重新添加了弗朗西斯已经给出的答案:

int op_index; // <-- not initialized.

并确保在编译器标志中使用 -Wall。

(另外为 Francis 的评论添加了 +1。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-25
    • 2011-02-27
    • 2015-01-26
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2011-07-10
    相关资源
    最近更新 更多