0

我有一个非常简单的 C 程序。我的程序使用我创建的一个非常简单的哈希文件。这是我的哈希文件:

const int SIZE = 26;

// A is 65 through Y is 89
int get_index(char key) {
   return ((int) key) - 65;
}

void reset_hash(int* hash) {
   int i = 0;
   for (; i < (SIZE - 1); i++) {
      hash[i] = 0;
   }
   hash[SIZE -1] = '\0';
}

int get_value(int* hash, char key) {
   return hash[get_index(key)];
}

void increment_value(int* hash, char key, int value) {
   hash[get_index(key)] = ++value;
}

如果绝对有必要,我可以解释为什么我的哈希函数如此简单。在这一点上我认为没有必要,但我可以告诉你,我的域非常简单且恒定,这就是为什么这个散列算法运行良好的原因。

现在,哈希是从另一个文件的主文件创建一次:

int* hash = calloc(SIZE_OF_AC, sizeof(int));

并且以不同的顺序从同一个文件中调用以下操作:

reset_hash(hash);
get_value(hash, /* some character here */);
increment_value(hash, /* some character here */, value);

我还多次传递散列指针,两个主要目标函数接收散列参数,如下所示:

int* hash

调用函数只是发送hash.

现在,我正在打印使用地址hash

printf("hash: %p\n", hash);

在我的主文件的一个地方,但由于该函数执行了多次而被打印了多次。这是我收到的输出:

hash: 0x801010
hash: 0x801010
hash: 0x3100000000801010
Segmentation fault (core dumped)

我的问题是,为什么我的哈希地址似乎发生了变化?考虑到我上面声明的操作,在 c 中的什么条件下 int* 的起始地址会发生变化?

如果您认为我遗漏了更多重要信息,我深表歉意。让我知道,我会发布更多。感谢您的任何回复。

4

1 回答 1

-1

index func 似乎有错误,不是吗?

// A is 65 through Y is 89
int get_index(char key) {
   return ((int) key) - 65;
}

应该是 (int) (key - 65) 吗?

于 2013-07-18T00:23:50.297 回答