gpt4 book ai didi

c - 我的指针错误地更改了地址

转载 作者:行者123 更新时间:2023-11-30 18:14:14 24 4
gpt4 key购买 nike

我有一个非常简单的 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 的地址:

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

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

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

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

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

最佳答案

索引函数似乎有错误,不是吗?

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

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

关于c - 我的指针错误地更改了地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17712285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com