在C++中返回简单哈希码的函数

Function returning simple hashcode in C++

本文关键字:哈希码 函数 简单 返回 C++      更新时间:2023-10-16

我正在尝试处理我C++书中的以下编程练习:"编写一个函数,该函数将字符串作为参数并返回原始哈希代码,该代码是通过将字符串中所有字符的值相加来计算的。

我的解决方案是:

#include <iostream>
#include <string>
#define clrscr() system("cls")
#define pause() system("pause")
using namespace std;
int hashc(char string[]);
int main()
{
    char phrase[256];
    cout << "This program converts any string into primitve hash-code." << "n";
    cout << "Input phrase: ";   cin.getline(phrase, sizeof(phrase));
    cout << "n";
    cout << "Hash-code for your phrase is: " << hashc(phrase) << "nn";
    pause();
    return(0);
}
int hashc(char string[])
{
    int index;
    int length;
    int hash_value = 0;
    length = strlen(string);
    for(index = 0; index >= length; ++index)
    {
        hash_value = hash_value + string[index];
    }

    return(hash_value);
}

问题是:该函数总是返回hash_value = 0,因为它似乎跳过了for循环。当我在函数中返回length时,它会返回给定字符串的正确长度(对于index = 0 index >= length)。因此,它通常应该触发 for 循环,不是吗?非常感谢这里的一点提示!

干杯!

惯用的 for 循环应如下所示:

for(index = 0; index < length; ++index)
{
    hash_value += string[index];
}

主要特点是索引从0(index = 0)开始,索引与长度"小于"(index < length)进行比较,并且,正如你所拥有的,索引使用预递增(++index)递增。

for(index = 0; index < length; ++index)

您目前从未进入循环,并且没有字符导致我的系统上出现分段错误。它进入循环的唯一情况是它通过条件(length >= index,即0>= 0),然后循环,直到它试图访问非法位置,此时发生seg错误。